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

knights.append('Sir Galahad the Chaste')
knights.append('Green Knight')
print(knights)

knights.insert(0, 'King Arthur')
knights.insert(2, 'Black Knight')
print(knights)

knights.pop()
print(knights)

knights.pop(2)
print(knights)

knights.extend(['Bors', 'Gawain', 'Ector'])
print(knights)

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

List Operators

The in membership operator works with lists.

print('Gawain' in knights)       # -> True
print('Michael Knight' in knights) # -> False

Looping Over Lists

To loop over lists, use a for in loop

for knight in knights:
    print(knight.upper())

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

for index in range(len(knights)):
    print(index, knights[i])

or use enumerate:

for i, knight in enumerate(knights):
    print(i, knight)

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.

numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
print(numbers[3::2])   # -> [3, 5, 7, 9]
print(numbers[8:3:-1]) # -> [8, 7, 6, 5, 4]

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

numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
digits = numbers[::]
print(digits) # -> [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

Last updated