This is an archived version of the course. Please see the latest version of the course.

Accessing Lists

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

>>> 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          

List slicing

Python also provides a convenient way to perform list slicing to slice out a subset of your list.

>>> print(students[1:4])     # ["Bella", "Connor", "Da-ming"]

I find the best way to think about “slicing” is to “slice” up your list between the elements, as in the image below.

Slicing a list

What happens when you do not provide a start or end index? Try these and see what happens!

>>> print(students[:3])
>>> print(students[2:])    
>>> print(students[:])    

Here are some more complicated slicing operations. Try to figure out what each is really doing (Google if you need to!)

>>> print(students[:])    
>>> print(students[0:5:2])
>>> print(students[:-3])
>>> print(students[-2:])
>>> print(students[::-1])      # this last one is an interesting Python 'idiom' or 'recipe'!