- We can access elements of the list either by using index or by using slice operator.
By using index
- List follows zero based index i.e. index of first element is zero.
- List supports both +ve and -ve indexes.
- +ve index meant for Left to Right
- -ve index meant for Right to Left
Example
Python
my_list = [10,20,30,40]
print(my_list[0])
print(my_list[-1])
print(my_list[10])
Output
PowerShell
10
40
IndexError: list index out of range
By using slice operator
Syntax
Python
subset_list = my_list[start, stop, step]
- start ⇒ It indicates the index where slice has to start. Default value is 0.
- stop ⇒ It indicates the index where slice has to end. Default value is length of the list.
- step ⇒ Increment value. Default value is 1.
Example
Python
n=[1,2,3,4,5,6,7,8,9,10]
print(n[2:7:2])
print(n[4::2])
print(n[3:7])
print(n[8:2:-2])
print(n[4:100])
Output
PowerShell
[3, 5, 7]
[5, 7, 9]
[4, 5, 6, 7]
[9, 7, 5]
[5, 6, 7, 8, 9, 10]
Mutability
- Once we creates a List object, we can modify its content. Hence List objects are mutable.
Example
Python
n=[10,20,30,40]
print(n)
n[1]=777
print(n)
Output
PowerShell
[10, 20, 30, 40]
[10, 777, 30, 40]
Traversing
- The sequential access of each element in the list is called traversal.
By using while loop
Python
n=[0,1,2,3,4,5,6,7,8,9,10]
i=0
while i<len(n):
print(n[i])
i=i+1
Output
PowerShell
0
1
2
3
4
5
6
7
8
9
10
By using for loop
Python
n=[0,1,2,3,4,5,6,7,8,9,]
for n1 in n:
print(n1)
Output
PowerShell
0
1
2
3
4
5
6
7
8
9
Question
Display only even numbers from list of element.
Python
n=[0,1,2,3,4,5,6,7,8,9,10]
for n1 in n:
if n1%2==0:
print(n1)
Output
PowerShell
0
2
4
6
8
10
Question
Display elements of list by index wise.
Python
l=["A","B","C"]
x=len(l)
for i in range(x):
print(l[i],"is available at positive index: ",i,"and at negative index: ",i-x)
Output
PowerShell
A is available at positive index: 0 and at negative index: -3
B is available at positive index: 1 and at negative index: -2
C is available at positive index: 2 and at negative index: -1
Ungraded Questions
Get ready for an exhilarating evaluation of your understanding! Brace yourself as we dive into the upcoming assessment. Your active participation is key, so make sure to attend and demonstrate your knowledge. Let’s embark on this exciting learning journey together!