Python List: a quick reference

A list has its items ordered and you can add the same item as many times as you want.

An important detail is that lists are mutable.

Initialization

Empty List

people = []

List with initial values

people = ['Bob', 'Mary']

Adding in a List

To add an item in the end of a list, use append().

people = ['Bob', 'Mary']
people.append('Sarah')

print(people)
['Bob', 'Mary', 'Sarah']

To specify the position for the new item, use the insert() method.

people = ['Bob', 'Mary']
people.insert(0, 'Sarah')

print(people)
['Sarah', 'Bob', 'Mary']

Updating in a List

Specify the position of the item to update and set the new value

people = ['Bob', 'Mary']
people[1] = 'Sarah'
print(people)
['Bob', 'Sarah']

Deleting in a List

Use the remove() method to delete the item given as an argument.

people = ['Bob', 'Mary']
people.remove('Bob')
print(people)
['Mary']

To delete everybody, use the clear() method:

people = ['Bob', 'Mary']
people.clear()

Retrieving in a List

Use the index to reference the item.

Remember that the index starts at 0.

So to access the second item use the index 1.

people = ['Bob', 'Mary']
print(people[1])
Mary

Iterating over Lists

To print the keys:

people = ['Bob', 'Mary']

for person in people:
  print(person)
Bob
Mary

Check if a given item already exists in a List

people = ['Bob', 'Mary']

if 'Bob' in people:
  print('Bob exists!')
else:
  print('There is no Bob!')