0% completed
Lists in Python allow direct access to elements using indexing. Indexing helps retrieve individual elements based on their position in the list. Python provides two types of indexing:
0
for the first element, 1
for the second, and so on.-1
for the last element, -2
for the second-last, and so on.Additionally, Python allows accessing a range of elements using slicing and provides a way to check whether an element exists in a list.
In positive indexing, elements are counted from left to right, starting from 0
.
fruits[0]
retrieves "Apple"
, the first element.fruits[1]
retrieves "Banana"
, the second element.fruits[2]
retrieves "Cherry"
, the third element.fruits[3]
retrieves "Date"
, the fourth element.In negative indexing, elements are counted from right to left, starting from -1
.
fruits[-1]
retrieves "Date"
, the last element.fruits[-2]
retrieves "Cherry"
, the second last element.fruits[-3]
retrieves "Banana"
, the third last element.fruits[-4]
retrieves "Apple"
, the fourth last element.To check whether an element exists in a list, use the in
keyword.
"Cat" in animals
returns True
because "Cat"
is in the list."Lion" in animals
returns False
because "Lion"
is not in the list......
.....
.....