Chapter 4: Sequence types

Accessing list elements

face Josiah Wang

You can access an element in a list just like you would an array in Java.

>>> students = ["Abraham", "Bella", "Connor", "Da-ming", "Enya"]
>>> print(students[0]) # First element
Abraham
>>> print(students[1]) # Second element
Bella

Python also allows you to access elements in a list in a reverse order, with negative indices.

>>> print(students[-1]) # First element from the end
Enya
>>> print(students[-2]) # Second element from the end
Da-ming

Accessing elements in a list with indices

Another list inside a list? No problem!

>>> x = [1, 2, [3, 4, 5], 6]
>>> print(x[2])
[3, 4, 5]
>>> print(x[2][1])
4