2 min read

Accessing List Elements

Similar to strings, items are stored into a list according to their index. Any item can be accessed using its index value.

  • The list index can be either positive or negative integer.
  • The positive index starts from 0 and negative starts from -1.

For example:-

#Each element can be accessed by its index value
>>>list=[11,22,33,44,55,66,77,88,99]
>>>list1[0]
11
#Negative values can also be used here
>>>list1[-2] # Here -2 will be treated as length of list-2
88
>>>list1[-5]
55

Traversing a list

Traversing means to travel across a list or to access all of its elements(items).

There are two ways to traverse a list in Python:

Using ‘in’ operator

  • ‘in’ operator is used to check whether the element is present in the list or not.
  • If you want to check the character is present in the list or not you can use this operator. It is useful in that case.
  • It can be used in for loop as iterator on the list. As shown in the below example.
>>>list1=['F','R','E','S','H','L','Y','B','U','I','L','T']
>>>for i in list1:
>>>    print(i)  #Here i is the iterator
F
R
E
S
H
L
Y
B
U
I
L
T

Using range() function

  • range() function in python is used for transversing of the list.
  • The numerical value or range value is passed inside the function for providing transversing limit.
  • It can also be used for traversing the list by leaving the element inside the list in a fixed manner.
  • For example, is we have to traverse over ‘ram’ we can also transverse over ‘ram’ by iterating over ‘r’ and ‘m’ and leaving a behind i.e range(3,1) # 3 equal to length of the word and 1 signify that we have to leave single character after taking out one character while traversing over the list.
>>>list1=['F','R','E','S','H','L','Y','B','U','I','L','T']
>>>n=len(list1) #here n is length of the list
>>>for i in range(n):
>>>    print(list1[i])  #Here i is the iterator
F
R
E
S
H
L
Y
B
U
I
L
T
Categories: Uncategorized

Kapil Bansal

A student of B.Tech CSE working on competitive programming, a cybersecurity devotee working towards strengthing the concepts. I am also working on Python modules, Data Structures and Algorithms etc.

0 Comments

Leave a Reply