Python List and Tuple Cheat Sheet

Lists #

['cat', 'bat', 'rat', 'elephant']

Getting Individual Values in a List with Indexes #

spam = ['cat', 'bat', 'rat', 'elephant']
spam[0]
spam[1]
spam[2]
spam[3]

Negative Indexes #

spam = ['cat', 'bat', 'rat', 'elephant']
spam[-1]
spam[-3]
'The {} is afraid of the {}.'.format(spam[-1], spam[-3])

Getting Sublists with Slices #

spam = ['cat', 'bat', 'rat', 'elephant']
spam[0:4]
spam[1:3]
spam[0:-1]
spam = ['cat', 'bat', 'rat', 'elephant']
spam[:2]
spam[1:]
spam[:]

Getting a list Length with len #

spam = ['cat', 'dog', 'moose']
len(spam)

Changing Values in a List with Indexes #

spam = ['cat', 'bat', 'rat', 'elephant']
spam[1] = 'aardvark'
spam
spam[2] = spam[1]
spam
spam[-1] = 12345
spam

List Concatenation and List Replication #

[1, 2, 3] + ['A', 'B', 'C']
['X', 'Y', 'Z'] * 3
spam = [1, 2, 3]
spam = spam + ['A', 'B', 'C']
spam

Removing Values from Lists with del Statements #

spam = ['cat', 'bat', 'rat', 'elephant']
del spam[2]
spam
del spam[2]
spam

Using for Loops with Lists #

supplies = ['pens', 'staplers', 'flame-throwers', 'binders']

for i, supply in enumerate(supplies):
    print('Index {} in supplies is: {}'.format(str(i), supply))

Looping Through Multiple Lists with zip #

name = ['Pete', 'John', 'Elizabeth']
age = [6, 23, 44]

for n, a in zip(name, age):
    print('{} is {} years old'.format(n, a))

The in and not in Operators #

'howdy' in ['hello', 'hi', 'howdy', 'heyas']
spam = ['hello', 'hi', 'howdy', 'heyas']
False
'howdy' not in spam
'cat' not in spam

The Multiple Assignment Trick #

The multiple assignment trick is a shortcut that lets you assign multiple variables with the values in a list in one line of code. So instead of doing this:

cat = ['fat', 'orange', 'loud']
size = cat[0]
color = cat[1]
disposition = cat[2]

You could type this line of code:

cat = ['fat', 'orange', 'loud']
size, color, disposition = cat

The multiple assignment trick can also be used to swap the values in two variables:

a, b = 'Alice', 'Bob'
a, b = b, a
print(a)
print(b)

Augmented Assignment Operators #

Operator Equivalent
spam += 1 spam = spam + 1
spam -= 1 spam = spam - 1
spam *= 1 spam = spam * 1
spam /= 1 spam = spam / 1
spam %= 1 spam = spam % 1

Examples:

spam = 'Hello'
spam += ' world!'
spam
bacon = ['Zophie']
bacon *= 3
bacon

Finding a Value in a List with the index Method #

spam = ['Zophie', 'Pooka', 'Fat-tail', 'Pooka']
spam.index('Pooka')

Adding Values to Lists with append and insert #

append():

spam = ['cat', 'dog', 'bat']
spam.append('moose')
spam

insert():

spam = ['cat', 'dog', 'bat']
spam.insert(1, 'chicken')
spam

Removing Values from Lists with remove #

spam = ['cat', 'bat', 'rat', 'elephant']
spam.remove('bat')
spam

If the value appears multiple times in the list, only the first instance of the value will be removed.

Sorting the Values in a List with sort #

spam = [2, 5, 3.14, 1, -7]
spam.sort()
spam
spam = ['ants', 'cats', 'dogs', 'badgers', 'elephants']
spam.sort()
spam

You can also pass True for the reverse keyword argument to have sort() sort the values in reverse order:

spam.sort(reverse=True)
spam

If you need to sort the values in regular alphabetical order, pass str. lower for the key keyword argument in the sort() method call:

spam = ['a', 'z', 'A', 'Z']
spam.sort(key=str.lower)
spam

You can use the built-in function sorted to return a new list:

spam = ['ants', 'cats', 'dogs', 'badgers', 'elephants']
sorted(spam)

Tuple Data Type #

eggs = ('hello', 42, 0.5)
eggs[0]
eggs[1:3]
len(eggs)

The main way that tuples are different from lists is that tuples, like strings, are immutable.

Converting Types with the list and tuple Functions #

tuple(['cat', 'dog', 5])
list(('cat', 'dog', 5))
list('hello')