CBSE Class 11 Python List

# CBSE Class 11: Python List 2

How to access elements from a list?

There are various ways in which we can access the elements of a list.

List Index

We can use the index operator [ ] to access an item in a list. Index starts from 0. So, a list having 5 elements will have index from 0 to 4.

Note : Trying to access an element other then the range will raise an IndexError. The index must be an integer. We can’t use float or other types, this will result into TypeError.

Nested list are accessed using nested indexing.

```n1=['c','o','m','p','u','t','e','r']
print(n1)
print(n1[0])
print(n1[2])
print(n1[4])```

Output

[‘c’, ‘o’, ‘m’, ‘p’, ‘u’, ‘t’, ‘e’, ‘r’]
c
m
u
>>>

```n2=['c','a','t','a','l','y','s','t']
print(n2)
print(n2[0])
print(n2[2])
print(n2[5])
print(n2[7])
print(n2[1])```

#Output

[‘c’, ‘a’, ‘t’, ‘a’, ‘l’, ‘y’, ‘s’, ‘t’]
c
t
y
t
a
>>>

Example of Nested List

n = [“Happy”, [2,0,1,5]]
# Nested indexing
print(n[0][0])
# Output: H
print(n[0][1])
# Output: a
print(n[1][0])
# Output: 2
print(n[1][1])
# Output: 0
print(n[1][3])
# Output: 5

Output:
H
a
2
0
5

```# Nested indexing
n = ["Happy", [2,0,1,5]]
print(n[0][0])
print(n[0][1])
print(n[1][0])
print(n[1][1])
print(n[1][3])
```

Output:

H
a
2
0
5

Important Pages