Lists

Lists are a mutable sequence of values of any type.

knights = ['Sir Bedevere the Wise', 'Sir Lancelot the Brave', 'Sir Robin the Not-Quite-So-Brave-As-Sir-Lancelot']

You can have mixed types in a list.

my_list = ['one', 2, 3.3333, True]

Lists are 0-indexed. Each element in the list can be accessed using bracket notation and its index number.

print(knights[0]) # -> 'Sir Bedevere the Wise'
print(knights[4]) # -> IndexError

You can use negative indices to access elements starting from the end

print(knights[-1]) # -> 'Sir Robin the Not-Quite-So-Brave-As-Sir-Lancelot'
print(knights[-2]) # -> 'Sir Lancelot the Brave'
print(knights[-4]) # -> IndexError

Get the number of elements a list with the len function

print(len(knights))

List Methods

Lists have a lot of useful methods. Here are a few:

append

add an element to the end of the list

insert

add an element at the specified position

pop

remove an element at the specified position (last by default)

extend

add elements of an iterable to the end of the list

For more list methods: https://www.w3schools.com/python/python_ref_list.asp

List Operators

The in membership operator works with lists.

Looping Over Lists

To loop over lists, use a for in loop

If you need access to the index number, use range and len:

or use enumerate:

Slicing

Python's slice operator : works with sequence types (strings, lists, tuples, etc.).

The syntax is a[start:stop:step], where start is inclusive and stop is not.

start, stop, and step have default values of 0, the length of the sequence being sliced, and 1 respectively.

Last updated

Was this helpful?