Python Lists 1
Python Lists 1
>>> spam
>>> spam[0]
'cat'
>>> spam[1]
'bat'
>>> spam[2]
'rat'
>>> spam[3]
'elephant'
Negative Indexes
>>> spam = ['cat', 'bat', 'rat', 'elephant']
>>> spam[-1]
'elephant'
>>> spam[-3]
'bat'
>>> spam[1:3]
['bat', 'rat']
>>> spam[0:-1]
['cat', 'bat']
>>> spam[1:]
>>> spam.append('dog')
>>> spam
3
Changing Values in a List with
Indexes >>> spam = ['cat', 'bat', 'rat',
>>> spam
>>> spam
>>> spam
>>> spam
>>> spam
>>> spam
['cat', 'bat']
'heyas'] True
False
False
True
The multiple assignment trick can also be used to swap the values in two
>>> a, b = b, a
>>> print(a)
'Bob'
>>> print(b)
'Alice'
Operator
spam /= 1
spam += 1
spam %= 1
spam -= 1
Examples:
>>> bacon *= 3
>>> bacon
>>> spam.index('Pooka')
>>> spam.append('moose')
>>> spam
>>> spam.remove('bat')
>>> spam
If the value appears multiple times in the list, only the first instance of the value will be
removed.
>>> spam.sort()
>>> spam
[-7, 1, 2, 3.14, 5]
>>> spam
['ants', 'badgers', 'cats', 'dogs', 'elephants']
You can also pass True for the reverse keyword argument to have sort() sort the
values in reverse order:
>>> spam.sort(reverse=True)
>>> spam
>>> spam.sort(key=str.lower)
>>> spam
You can use the built-in function sorted to return a new list:
>>> eggs[0]
'hello'
>>> eggs[1:3]
(42, 0.5)
>>> len(eggs)
The main way that tuples are different from lists is that tuples, like strings, are
immutable.
('cat', 'dog', 5)
['cat', 'dog', 5]
>>> list('hello')