Python Data Structures
Python Data Structures
STRUCTURES
list.append(x)
Add an item to the end of the list. Equivalent to a[len(a):] = [x].
list.extend(iterable )
Extend the list by appending all the items from the iterable. Equivalent
to a[len(a):] = iterable.
list.insert(i, x)
Insert an item at a given position. The first argument is the index of the element
before which to insert, so a.insert(0, x) inserts at the front of the list,
and a.insert(len(a), x) is equivalent to a.append(x).
list.remove(x)
Remove the first item from the list whose value is equal to x. It raises
a ValueError if there is no such item.
list.pop ([i])
Remove the item at the given position in the list, and return it. If no index is
specified, a.pop() removes and returns the last item in the list. (The square
brackets around the i in the method signature denote that the parameter is
optional, not that you should type square brackets at that position. You will see
this notation frequently in the Python Library Reference.)
list.clear()
Remove all items from the list. Equivalent to del a[:].
The optional arguments start and end are interpreted as in the slice notation and
are used to limit the search to a particular subsequence of the list. The returned
index is computed relative to the beginning of the full sequence rather than
the start argument.
list.count(x)
Return the number of times x appears in the list.
list.reverse()
Reverse the elements of the list in place.
list.copy ()
Return a shallow copy of the list. Equivalent to a[:].
>>>
>>> t = 12345, 54321, 'hello!'
>>> t[0]
12345
>>> 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:
... t[0] = 88888
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'tuple' object does not support item assignment
>>> # but they can contain mutable objects:
... v = ([1, 2, 3], [3, 2, 1])
>>> v
([1, 2, 3], [3, 2, 1])
As you see, on output tuples are always enclosed in parentheses, so that nested tuples
are interpreted correctly; they may be input with or without surrounding parentheses,
although often parentheses are necessary anyway (if the tuple is part of a larger
expression). It is not possible to assign to the individual items of a tuple, how ever it is
possible to create tuples which contain mutable objects, such as lists.
Though tuples may seem similar to lists, they are often used in different situations and
for different purposes. Tuples are immutable, and usually contain a heterogeneous
sequence of elements that are accessed via unpacking (see later in this section) or
indexing (or even by attribute in the case of namedtuples). Lists are mutable, and their
elements are usually homogeneous and are accessed by iterating over the list.
A special problem is the construction of tuples containing 0 or 1 items: the syntax has
some extra quirks to accommodate these. Empty tuples are constructed by an empty
pair of parentheses; a tuple with one item is constructed by following a value with a
comma (it is not sufficient to enclose a single value in parentheses). Ugly, but effective.
For example:
>>>
>>> empty = ()
>>> singleton = 'hello', # <-- note trailing comma
>>> len(empty)
0
>>> len(singleton)
1
>>> singleton
('hello',)
>>>
>>> x, y, z = t
This is called, appropriately enough, sequence unpacking and works for any sequence
on the right-hand side. Sequence unpacking requires that there are as many variables
on the left side of the equals sign as there are elements in the sequence. Note that
multiple assignment is really just a combination of tuple packing and sequence
unpacking.
SETS
Python also includes a data type for sets. A set is an unordered collection with no
duplicate elements. Basic uses include membership testing and eliminating duplicate
entries. Set objects also support mathematical operations like union, intersection,
difference, and symmetric difference.
Curly braces or the set() function can be used to create sets. Note: to create an empty
set you have to use set(), not {}; the latter creates an empty dictionary, a data
structure that we discuss in the next section.
>>>
>>> basket = {'apple', 'orange', 'apple', 'pear', 'orange',
'banana'}
>>> print(basket) # show that duplicates have
been removed
{'orange', 'banana', 'pear', 'apple'}
>>> 'orange' in basket # fast membership testing
True
>>> 'crabgrass' in basket
False
>>>
>>> a = {x for x in 'abracadabra' if x not in 'abc'}
>>> a
{'r', 'd'}
DICTIONARIES
Another useful data type built into Python is the dictionary (see Mapping Types — dict).
Dictionaries are sometimes found in other languages as “associative memories” or
“associative arrays”. Unlike sequences, which are indexed by a range of numbers,
dictionaries are indexed by keys, which can be any immutable type; strings and
numbers can always be keys. Tuples can be used as keys if they contain only strings,
numbers, or tuples; if a tuple contains any mutable object either directly or indirectly, it
cannot be used as a key. You can’t use lists as keys, since lists can be modified in
place using index assignments, slice assignments, or methods
like append() and extend().
It is best to think of a dictionary as a set of key: value pairs, with the requirement that
the keys are unique (within one dictionary). A pair of braces creates an empty
dictionary: {}. Placing a comma-separated list of key:value pairs within the braces adds
initial key:value pairs to the dictionary; this is also the way dictionaries are written on
output.
The main operations on a dictionary are storing a value with some key and extracting
the value given the key. It is also possible to delete a key:value pair with del. If you
store using a key that is already in use, the old value associated with that key is
forgotten. It is an error to extract a value using a non-existent key.
Performing list(d) on a dictionary returns a list of all the keys used in the dictionary,
in insertion order (if you want it sorted, just use sorted(d) instead). To check whether
a single key is in the dictionary, use the in keyword.
Here is a small example using a dictionary:
>>>
>>> tel = {'jack': 4098, 'sape': 4139}
>>> tel['guido'] = 4127
>>> tel
{'jack': 4098, 'sape': 4139, 'guido': 4127}
>>> tel['jack']
4098
>>> del tel['sape']
>>> tel['irv'] = 4127
>>> tel
{'jack': 4098, 'guido': 4127, 'irv': 4127}
>>> list(tel)
['jack', 'guido', 'irv']
>>> sorted(tel)
['guido', 'irv', 'jack']
>>> 'guido' in tel
True
>>> 'jack' not in tel
False
The dict() constructor builds dictionaries directly from sequences of key-value pairs:
>>>
>>> dict([('sape', 4139), ('guido', 4127), ('jack', 4098)])
{'sape': 4139, 'guido': 4127, 'jack': 4098}
In addition, dict comprehensions can be used to create dictionaries from arbitrary key
and value expressions:
>>>
>>> {x: x**2 for x in (2, 4, 6)}
{2: 4, 4: 16, 6: 36}
When the keys are simple strings, it is sometimes easier to specify pairs using keyword
arguments:
>>>
>>> dict(sape=4139, guido=4127, jack=4098)
{'sape': 4139, 'guido': 4127, 'jack': 4098}
Credit: Python Documentation.