{:check ["true"], :rank ["list" "list_memory_model" "tuple" "set" "dict"]}
Python list is arguably the most versatile compound data types.
One can construct lists with the list syntax:
[ ... ]
. Elements are separated by ,
.
>>> squares = [1, 4, 9, 16, 25]
>>> squares
[1, 4, 9, 16, 25]
>>> len(squares)
5
>>> squares[0] # indexing returns the item
1
>>> squares[-1]
25
# indexing from start to end
# start - inclusive
# end - exclusive
>>> squares[0:3]
[1, 4, 9]
>>> squares[1:3]
[4, 9]
# start can be omitted, the
# default start is 0.
>>> squares[:3]
[1, 4, 9]
>>> squares[:5]
[1, 4, 9, 16, 25]
# the end can be omitted, and
# the default end is the
# length of the list.
>>> squares[3:]
[16, 25]
>>> squares[:]
[1, 4, 9, 16, 25]
Consider the following code operating on Python lists:
x = [1]
y = [2]
z = [3]
list1 = [x, y, z]
>>> print(list1)
[[1], [2], [3]]
+-----+-----+-----+
| * | * | * |
+--|--+--|--+--|--+
| | |
| | |
x | y | z |
\ | \ | \ |
\ | \ | \ |
+---+ +---+ +---+
| 1 | | 2 | | 3 |
+---+ +---+ +---+
Modifying x
will also affect the content of list
>>> x[0] = -1 >>> print(list1) [[-1], [2], [3]]
Modifying list
will also affect the
Tuples are immutable lists.
Construction (__, __, __)
. The parenthese are optional.
>>> t = (12345, 54321, 'hello!')
>>> t = 12345, 54321, 'hello!'
Indexing is the same as lists
>>> t[0]
12345
Tuples can be nested.
>>> t
(12345, 54321, 'hello!')
>>> # Tuples may be nested:
... u = t, (1, 2, 3, 4, 5)
>>> u
((12345, 54321, 'hello!'), (1, 2, 3, 4, 5))
Tuples are immutable. We cannot change the tuple value.
>>> # Tuples are immutable:
... t[0] = 88888
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'tuple' object does not support item assignment
However, if the elements are mutable data structures, we can update the element values themselves.
>>> # but they can contain mutable objects:
... v = ([1, 2, 3], [3, 2, 1])
>>> v
([1, 2, 3], [3, 2, 1])
>>> v[0].append(4)
>>> v
([1, 2, 3, 4], [3, 2, 1])
Tuples can be empty. The parentheses are necessary.
empty = ()
Singletons are tuples with just one element. The syntax requires the trailing comma ,
. The parentheses are optional.
one_thing = ('hello',)
one_thing = 'hello',
We can unpack the tuples into variables.
>>> t
(12345, 54321, 'hello')
>>> x,y,z = t
>>> x
12345
>>> y
54321
>>> z
"hello"
A set is a collection with no ordering and does not allow duplicate elements.
The construction of set is done with the curly braces.
>>> basket = {'apple', 'orange', 'apple', 'pear', 'orange', 'banana'}
>>> print(basket) # show that duplicates have been removed
{'orange', 'banana', 'pear', 'apple'}
We can check if a element belongs to a set with the in
operator.
>>> 'orange' in basket # fast membership testing
True
>>> 'crabgrass' in basket
False
The set(...)
function converts a sequence into a set by
removing any duplicates.
>>> # Demonstrate set operations on unique letters from two words
...
>>> a = set('abracadabra')
>>> b = set('alacazam')
>>> a # unique letters in a
{'a', 'r', 'b', 'c', 'd'}
Set arithmetics are:
>>> a - b # letters in a but not in b
{'r', 'd', 'b'}
>>> a | b # letters in a or b or both
{'a', 'c', 'r', 'd', 'b', 'm', 'z', 'l'}
>>> a & b # letters in both a and b
{'a', 'c'}
>>> a ^ b # letters in a or b but not both
{'r', 'd', 'b', 'm', 'z', 'l'}
Dictionary is one of the most important data type in Python. Unlike lists, the elements are indexed by arbitrary (immutable) values.
Definition
- Indexing values are the keys in the dictionary.
- The indexed elements are the values in the dictionary.
All keys must be unique, but not the values.
Construction using { key:val, ...}
>>> tel = {'jack': 4098, 'sape': 4139}
Construction using the dict(...)
constructor:
>>> tel = dict(jack=4098, sape=4139)
Construction using dict(...)
to construct
the dictionary from a sequence of key/value pairs.
>>> dict([('sape', 4139), ('guido', 4127), ('jack', 4098)])
{'sape': 4139, 'guido': 4127, 'jack': 4098}
We can retrieve the value of a given key.
>>> tel['jack']
4098
We can create new key/value pairs in the dictionary.
>>> tel['guido'] = 4127
>>> tel
{'jack': 4098, 'sape': 4139, 'guido': 4127}
We can delete a key and its value.
>>> del tel['sape']
>>> tel['irv'] = 4127
>>> tel
{'jack': 4098, 'guido': 4127, 'irv': 4127}
If we interprete a dictionary as a list, we get the list of keys.
>>> list(tel)
['jack', 'guido', 'irv']
>>> sorted(tel)
['guido', 'irv', 'jack']
We can also check if a key exists in a dictionary using the in
operator.
>>> 'guido' in tel
True
>>> 'jack' not in tel
False
We can get a sequence of key/value pairs (as tuples) using the .items()
method.
for (name, number) in tel.items():
print("%s: %s" % (name, number))