September 03, 2021    /    Viewed: 155    /    Comments: 0    /    Edit

Examples of how to select nth element in a list with python:

### Create a list

Let's first create a list with python:

````mylist = ['A', 'B', 'C', 'D', 'E', 'F']`
```

Note that a list is 0 based indexing.

index element
0 A
1 B
2 C
3 D
4 E
5 F

### Select the first element of a list

To select the first element of a list

````mylist[0]`
```

returns here

````'A'`
```

### Select the last element of a list

To select the last element of a list

````mylist[-1]`
```

returns here

````'F'`
```

### Select nth element of a list

To select nth element of a list

````mylist[4]`
```

returns here

````'E'`
```

However

````mylist[6]`
```

will returns the following error message

````IndexError: list index out of range`
```

since the list contains only 6 element.

To avoid that

````index = 6`
`if index < len(mylist):`
`    print(mylist[index])`
`else:`
`    print('Warning: list index out of range')`
```

or

````try:`
`    mylist[index]`
`except:`
`    pass`
```

### Find index of a given element

Note to find the index of a given element

````mylist.index('D')`
```

returns

````3`
```

Note: To check if an element is in a list:

````'D' in mylist`
```

returns

````True`
```

while

````'G' in mylist`
```

returns

````False`
```

### Loop through a list and print element with associated index

To loop through a list and print element with associated index, a solution is to use enumerate()

````for i,e in enumerate(mylist):`
`        print(i,e)`
```

returns here

````0 A`
`1 B`
`2 C`
`3 D`
`4 E`
`5 F`
```

### References

##### Daidalos

Hi, I am Ben.

I have developed this web site from scratch with Django to share with everyone my notes. If you have any ideas or suggestions to improve the site, let me know ! (you can contact me using the form in the welcome page). Thanks!