A list is a value that contains multiple values. The values in a list are also called items.
spam = ['cat', 'bat', 'rat', 'elephant']
spam
A list can hold multiple data types and you don't need to define how long the list will be beforehand (dynamic array)
spam = ['hi', 1, 2, 3]
spam
You can access items in a list with it's integer index which starts at 0, not 1
spam[0]
spam = [['cat', 'bat'], [10, 20, 30]]
spam[0]
spam[1][1]
You can also use negative indexes. -1 refers to the last item. -2 refers to the second to last item, and so on
spam = ['cat', 'bat', 'rat', 'elephant']
spam[-1] # 'elephant'
spam[-2] # 'rat'
'The ' + spam[-1] + ' is fat'
You can get multiple items from the list using a slice. The slice has two indexes. The new list's items start at the first index and go up to, but does not include, the second index
spam = ['cat', 'bat', 'rat', 'elephant']
spam[1:3]
spam = ['cat', 'bat', 'rat', 'elephant']
spam[:2]
spam[1:]
spam = [10, 20, 30]
spam[1] = 'Hello'
spam
spam[1:3] = ['CAT', 'DOG', 'MOUSE']
spam
You can remove an item from a list by using del
. Think of del
as an un-assignment statement
spam = ['cat', 'bat', 'rat', 'elephant']
del spam[2]
spam
del spam[2]
spam
The len()
function, concatenation, and replication work the same way with lists that they do with strings
String | List | |
---|---|---|
Length | len('Hello') # 5 | len([1, 2, 3]) # 3 |
Concatenation | 'Hello'+' World' # 'Hello World' | [1, 2] + [5, 6] # [1, 2, 5, 6] |
Replication | 'Hello' * 2 # 'HelloHello' | [1, 2] * 2 # [1, 2, 1, 2] |
You can convert a value into a list by passing it to the list()
function
list('Hello')
'howdy' in ['hello', 'hi', 'howdy', 'heyas']
42 in ['hello', 'hi', 'howdy', 'heyas']
'howdy' not in ['hello', 'hi', 'howdy', 'heyas']
range(4)
The range()
function can be passed to the list()
function if you need an actual list value
list(range(4))
list(range(2, 10, 2))
For loops technically iterate over the values in a list
for i in range(4):
print(i)
which is the same as:
for i in [0, 1, 2, 3]:
print(i)
supplies = ['pens', 'staplers', 'flame-throwers', 'binders']
for i in range(len(supplies)):
print('Index ' + str(i) + ':' + supplies[i])
Variables can swap their values using multiple assignments
cat = ['fat', 'orange', 'loud']
size, color, disposition = cat
size
color
disposition
size, color, disposition = 'skinny', 'black', 'quiet'
size
color
disposition
a = 'AAA'
b = 'BBB'
a, b = b, a
a
b
Augmented Assignment Operators like +=
are used as shortcuts
Augmented assignment statement | Equivalent assignment statement |
---|---|
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 |
spam = 42
spam = spam + 1
spam += 1
spam
spam = ['hello', 'hi', 'howdy', 'heyas']
spam.index('hello')
# spam.index('bla') #ValueError
Duplicate values in list
spam = ['Sophie', 'Pooka', 'Fat-tail', 'Pooka']
spam.index('Pooka')
The append()
list method adds a value to the end of a list. The insert()
method adds a value anywhere inside a list. Both methods returns None
value.
spam = ['cat', 'dog', 'bat']
spam.append('mouse')
spam
spam = ['cat', 'dog', 'bat']
spam.insert(1, 'chicken')
spam
The remove()
list method removes an item, specified by a value, from a list (compare to del
statement which specify the index)
spam = ['cat', 'bat', 'rat', 'elephant']
spam.remove('bat')
spam
# spam.remove('blah') # ValueError
del spam[0]
spam
The remove()
list method can only remove 1 item from the list
spam = ['cat', 'bat', 'rat', 'cat']
spam.remove('cat')
spam
The pop()
list method will remove an item in the list. The default is the last item but you can also specify the index of item to be removed
myList = [1,2,3,4]
myList.pop()
myList = [1,2,3,4]
myList.pop(0)
The sort()
list method sorts the items in a list
spam = [2, 5, 3.14, 1, -7]
spam.sort()
spam
spam = ['dogs', 'cats', 'ants']
spam.sort()
spam
The sort()
method's reverse=True
keyword argument can sort in reverse order
spam = ['dogs', 'cats', 'ants']
spam.sort(reverse = True)
spam
spam = [1, 'Alice', 33]
# spam.sort() # TypeError
By default, sort()
happens in ASCII-betical i.e. uppercase characters come before lowercase characters.
spam = ['Alice', 'carol', 'ants', 'Bob']
spam.sort()
spam
To sort in true alphabetical order, pass key=str.lower
spam = ['a', 'Z', 'A', 'z']
spam.sort(key = str.lower)
spam
Use the sum() list method to sum up list of numbers
spam = [2,3,4]
sum(spam)
Strings can do a lot of things like lists can do, but strings are immutable.
list("Hello")
name = 'Zophie'
name[0]
name[1:3]
name[-2]
'Zo' in name
'xxx' in name
for letter in name:
print(letter)
Immutable values can't be modified "in place" e.g. strings, tuples. You can't actually change an item once it's in there
name = 'Zophie the cat'
name[7]
# name[7] = 'X' # TypeError
You modify strings by creating New Strings from Slice
name = 'Zophie a cat'
newName = name[0:7] + 'the' + name[8:12]
newName
Mutable values can be modified "in place" e.g. lists. You can modify an item in a list
myList = [1,2,3]
myList[0] = 'New'
myList
The difference between immutable and mutable comes up with "references".
spam = 42
cheese = spam
spam = 100
spam
cheese
Variables don't contain lists, they contain reference to lists.
spam = [0, 1, 2, 3, 4, 5]
cheese = spam
cheese[1] = 'Hello'
cheese
spam
spam = [0, 1, 2, 3, 4, 5] stores the reference to the list, not the actual list
cheese = spam copies the reference, not the list
cheese[1] = 'Hello' modifies the list that both variables refer to
Immutable values such as strings don't have this problem because they can't be modified "in place". They can only be replaced by new values.
References are explained very well in Ned Batchelder's talk, "Facts and myths about Python names and values" (25 minutes)
When passing a list argument to a function, you are actually passing a list reference, NOT a copy of a list. Change made in a list in a function will affect the list outside the function.
def eggs(cheese):
cheese.append('Hello')
spam = [1, 2, 3]
eggs(spam)
print(spam)
import copy
spam = ['A', 'B', 'C', 'D']
cheese = copy.deepcopy(spam)
cheese[1] = 42
cheese
spam
The \
line continuation character can be used to strech Python instructions across multiple lines. This is the exception to the rule about block and indentation.
spam = ['apples',
'oranges',
'bananas']
spam
print('Four score and seven' + \
' years ago...')
x = [1,2,3,4]
out = []
for num in x:
out.append(num**2)
out
which is the same as:
x = [1,2,3,4]
out1 = [num**2 for num in x]
out1