blob: 54d1922b717added19c25bc371998b695bfbcaf2 [file] [log] [blame]
Georg Brandl116aa622007-08-15 14:28:22 +00001.. _tut-structures:
2
3***************
4Data Structures
5***************
6
7This chapter describes some things you've learned about already in more detail,
8and adds some new things as well.
9
Guido van Rossum0616b792007-08-31 03:25:11 +000010.. _tut-tuples:
11
12Tuples and Sequences
13====================
14
15We saw that lists and strings have many common properties, such as indexing and
16slicing operations. They are two examples of *sequence* data types (see
17:ref:`typesseq`). Since Python is an evolving language, other sequence data
18types may be added. There is also another standard sequence data type: the
19*tuple*.
20
21A tuple consists of a number of values separated by commas, for instance::
22
23 >>> t = 12345, 54321, 'hello!'
24 >>> t[0]
25 12345
26 >>> t
27 (12345, 54321, 'hello!')
28 >>> # Tuples may be nested:
29 ... u = t, (1, 2, 3, 4, 5)
30 >>> u
31 ((12345, 54321, 'hello!'), (1, 2, 3, 4, 5))
32
33As you see, on output tuples are always enclosed in parentheses, so that nested
34tuples are interpreted correctly; they may be input with or without surrounding
35parentheses, although often parentheses are necessary anyway (if the tuple is
36part of a larger expression).
37
38Tuples have many uses. For example: (x, y) coordinate pairs, employee records
39from a database, etc. Tuples, like strings, are immutable: it is not possible
40to assign to the individual items of a tuple (you can simulate much of the same
41effect with slicing and concatenation, though). It is also possible to create
42tuples which contain mutable objects, such as lists.
43
44A special problem is the construction of tuples containing 0 or 1 items: the
45syntax has some extra quirks to accommodate these. Empty tuples are constructed
46by an empty pair of parentheses; a tuple with one item is constructed by
47following a value with a comma (it is not sufficient to enclose a single value
48in parentheses). Ugly, but effective. For example::
49
50 >>> empty = ()
51 >>> singleton = 'hello', # <-- note trailing comma
52 >>> len(empty)
53 0
54 >>> len(singleton)
55 1
56 >>> singleton
57 ('hello',)
58
59The statement ``t = 12345, 54321, 'hello!'`` is an example of *tuple packing*:
60the values ``12345``, ``54321`` and ``'hello!'`` are packed together in a tuple.
61The reverse operation is also possible::
62
63 >>> x, y, z = t
64
65This is called, appropriately enough, *sequence unpacking*. Sequence unpacking
66requires the list of variables on the left to have the same number of elements
67as the length of the sequence. Note that multiple assignment is really just a
68combination of tuple packing and sequence unpacking!
69
70There is a small bit of asymmetry here: packing multiple values always creates
71a tuple, and unpacking works for any sequence.
72
73.. % XXX Add a bit on the difference between tuples and lists.
74
Georg Brandl116aa622007-08-15 14:28:22 +000075
76.. _tut-morelists:
77
78More on Lists
79=============
80
81The list data type has some more methods. Here are all of the methods of list
82objects:
83
84
85.. method:: list.append(x)
86
87 Add an item to the end of the list; equivalent to ``a[len(a):] = [x]``.
88
89
90.. method:: list.extend(L)
91
92 Extend the list by appending all the items in the given list; equivalent to
93 ``a[len(a):] = L``.
94
95
96.. method:: list.insert(i, x)
97
98 Insert an item at a given position. The first argument is the index of the
99 element before which to insert, so ``a.insert(0, x)`` inserts at the front of
100 the list, and ``a.insert(len(a), x)`` is equivalent to ``a.append(x)``.
101
102
103.. method:: list.remove(x)
104
105 Remove the first item from the list whose value is *x*. It is an error if there
106 is no such item.
107
108
109.. method:: list.pop([i])
110
111 Remove the item at the given position in the list, and return it. If no index
112 is specified, ``a.pop()`` removes and returns the last item in the list. (The
113 square brackets around the *i* in the method signature denote that the parameter
114 is optional, not that you should type square brackets at that position. You
115 will see this notation frequently in the Python Library Reference.)
116
117
118.. method:: list.index(x)
119
120 Return the index in the list of the first item whose value is *x*. It is an
121 error if there is no such item.
122
123
124.. method:: list.count(x)
125
126 Return the number of times *x* appears in the list.
127
128
129.. method:: list.sort()
130
131 Sort the items of the list, in place.
132
133
134.. method:: list.reverse()
135
136 Reverse the elements of the list, in place.
137
138An example that uses most of the list methods::
139
140 >>> a = [66.25, 333, 333, 1, 1234.5]
Guido van Rossum0616b792007-08-31 03:25:11 +0000141 >>> print(a.count(333), a.count(66.25), a.count('x'))
Georg Brandl116aa622007-08-15 14:28:22 +0000142 2 1 0
143 >>> a.insert(2, -1)
144 >>> a.append(333)
145 >>> a
146 [66.25, 333, -1, 333, 1, 1234.5, 333]
147 >>> a.index(333)
148 1
149 >>> a.remove(333)
150 >>> a
151 [66.25, -1, 333, 1, 1234.5, 333]
152 >>> a.reverse()
153 >>> a
154 [333, 1234.5, 1, 333, -1, 66.25]
155 >>> a.sort()
156 >>> a
157 [-1, 1, 66.25, 333, 333, 1234.5]
158
159
160.. _tut-lists-as-stacks:
161
162Using Lists as Stacks
163---------------------
164
165.. sectionauthor:: Ka-Ping Yee <ping@lfw.org>
166
167
168The list methods make it very easy to use a list as a stack, where the last
169element added is the first element retrieved ("last-in, first-out"). To add an
170item to the top of the stack, use :meth:`append`. To retrieve an item from the
171top of the stack, use :meth:`pop` without an explicit index. For example::
172
173 >>> stack = [3, 4, 5]
174 >>> stack.append(6)
175 >>> stack.append(7)
176 >>> stack
177 [3, 4, 5, 6, 7]
178 >>> stack.pop()
179 7
180 >>> stack
181 [3, 4, 5, 6]
182 >>> stack.pop()
183 6
184 >>> stack.pop()
185 5
186 >>> stack
187 [3, 4]
188
189
190.. _tut-lists-as-queues:
191
192Using Lists as Queues
193---------------------
194
195.. sectionauthor:: Ka-Ping Yee <ping@lfw.org>
196
197
198You can also use a list conveniently as a queue, where the first element added
199is the first element retrieved ("first-in, first-out"). To add an item to the
200back of the queue, use :meth:`append`. To retrieve an item from the front of
201the queue, use :meth:`pop` with ``0`` as the index. For example::
202
203 >>> queue = ["Eric", "John", "Michael"]
204 >>> queue.append("Terry") # Terry arrives
205 >>> queue.append("Graham") # Graham arrives
206 >>> queue.pop(0)
207 'Eric'
208 >>> queue.pop(0)
209 'John'
210 >>> queue
211 ['Michael', 'Terry', 'Graham']
212
213
Georg Brandl116aa622007-08-15 14:28:22 +0000214List Comprehensions
215-------------------
216
Guido van Rossum0616b792007-08-31 03:25:11 +0000217List comprehensions provide a concise way to create lists from sequences.
218Common applications are to make lists where each element is the result of
219some operations applied to each member of the sequence, or to create a
220subsequence of those elements that satisfy a certain condition.
221
222
Georg Brandl116aa622007-08-15 14:28:22 +0000223Each list comprehension consists of an expression followed by a :keyword:`for`
224clause, then zero or more :keyword:`for` or :keyword:`if` clauses. The result
225will be a list resulting from evaluating the expression in the context of the
226:keyword:`for` and :keyword:`if` clauses which follow it. If the expression
Guido van Rossum0616b792007-08-31 03:25:11 +0000227would evaluate to a tuple, it must be parenthesized.
228
229Here we take a list of numbers and return a list of three times each number::
230
231 >>> vec = [2, 4, 6]
232 >>> [3*x for x in vec]
233 [6, 12, 18]
234
235Now we get a little fancier::
236
Georg Brandle4ac7502007-09-03 07:10:24 +0000237 >>> [[x, x**2] for x in vec]
Guido van Rossum0616b792007-08-31 03:25:11 +0000238 [[2, 4], [4, 16], [6, 36]]
239
240Here we apply a method call to each item in a sequence::
Georg Brandl116aa622007-08-15 14:28:22 +0000241
242 >>> freshfruit = [' banana', ' loganberry ', 'passion fruit ']
243 >>> [weapon.strip() for weapon in freshfruit]
244 ['banana', 'loganberry', 'passion fruit']
Guido van Rossum0616b792007-08-31 03:25:11 +0000245
Georg Brandle4ac7502007-09-03 07:10:24 +0000246Using the :keyword:`if` clause we can filter the stream::
Guido van Rossum0616b792007-08-31 03:25:11 +0000247
Georg Brandl116aa622007-08-15 14:28:22 +0000248 >>> [3*x for x in vec if x > 3]
249 [12, 18]
250 >>> [3*x for x in vec if x < 2]
251 []
Guido van Rossum0616b792007-08-31 03:25:11 +0000252
253Tuples can often be created without their parentheses, but not here::
254
Georg Brandl116aa622007-08-15 14:28:22 +0000255 >>> [x, x**2 for x in vec] # error - parens required for tuples
256 File "<stdin>", line 1, in ?
257 [x, x**2 for x in vec]
258 ^
259 SyntaxError: invalid syntax
260 >>> [(x, x**2) for x in vec]
261 [(2, 4), (4, 16), (6, 36)]
Guido van Rossum0616b792007-08-31 03:25:11 +0000262
Georg Brandle4ac7502007-09-03 07:10:24 +0000263Here are some nested for loops and other fancy behavior::
Guido van Rossum0616b792007-08-31 03:25:11 +0000264
Georg Brandl116aa622007-08-15 14:28:22 +0000265 >>> vec1 = [2, 4, 6]
266 >>> vec2 = [4, 3, -9]
267 >>> [x*y for x in vec1 for y in vec2]
268 [8, 6, -18, 16, 12, -36, 24, 18, -54]
269 >>> [x+y for x in vec1 for y in vec2]
270 [6, 5, -7, 8, 7, -5, 10, 9, -3]
271 >>> [vec1[i]*vec2[i] for i in range(len(vec1))]
272 [8, 12, -54]
273
Guido van Rossum0616b792007-08-31 03:25:11 +0000274List comprehensions can be applied to complex expressions and nested functions::
Georg Brandl116aa622007-08-15 14:28:22 +0000275
Georg Brandle4ac7502007-09-03 07:10:24 +0000276 >>> [str(round(355/113.0, i)) for i in range(1, 6)]
Georg Brandl116aa622007-08-15 14:28:22 +0000277 ['3.1', '3.14', '3.142', '3.1416', '3.14159']
278
279
280.. _tut-del:
281
282The :keyword:`del` statement
283============================
284
285There is a way to remove an item from a list given its index instead of its
286value: the :keyword:`del` statement. This differs from the :meth:`pop` method
287which returns a value. The :keyword:`del` statement can also be used to remove
288slices from a list or clear the entire list (which we did earlier by assignment
289of an empty list to the slice). For example::
290
291 >>> a = [-1, 1, 66.25, 333, 333, 1234.5]
292 >>> del a[0]
293 >>> a
294 [1, 66.25, 333, 333, 1234.5]
295 >>> del a[2:4]
296 >>> a
297 [1, 66.25, 1234.5]
298 >>> del a[:]
299 >>> a
300 []
301
302:keyword:`del` can also be used to delete entire variables::
303
304 >>> del a
305
306Referencing the name ``a`` hereafter is an error (at least until another value
307is assigned to it). We'll find other uses for :keyword:`del` later.
308
309
Georg Brandl116aa622007-08-15 14:28:22 +0000310
311.. _tut-sets:
312
313Sets
314====
315
316Python also includes a data type for *sets*. A set is an unordered collection
317with no duplicate elements. Basic uses include membership testing and
318eliminating duplicate entries. Set objects also support mathematical operations
319like union, intersection, difference, and symmetric difference.
320
Guido van Rossum0616b792007-08-31 03:25:11 +0000321Curly braces or the :func:`set` function can be use to create sets. Note:
322To create an empty set you have to use set(), not {}; the latter creates
323an empty dictionary, a data structure that we discuss in the next section.
324
Georg Brandl116aa622007-08-15 14:28:22 +0000325Here is a brief demonstration::
326
Guido van Rossum0616b792007-08-31 03:25:11 +0000327 >>> basket = {'apple', 'orange', 'apple', 'pear', 'orange', 'banana'}
328 >>> print(basket)
329 {'orange', 'bananna', 'pear', 'apple'}
330 >>> fruit = ['apple', 'orange', 'apple', 'pear', 'orange', 'banana']
Georg Brandl116aa622007-08-15 14:28:22 +0000331 >>> fruit = set(basket) # create a set without duplicates
332 >>> fruit
Guido van Rossum0616b792007-08-31 03:25:11 +0000333 {'orange', 'pear', 'apple', 'banana'}
Georg Brandl116aa622007-08-15 14:28:22 +0000334 >>> 'orange' in fruit # fast membership testing
335 True
336 >>> 'crabgrass' in fruit
337 False
338
339 >>> # Demonstrate set operations on unique letters from two words
340 ...
341 >>> a = set('abracadabra')
342 >>> b = set('alacazam')
343 >>> a # unique letters in a
Guido van Rossum0616b792007-08-31 03:25:11 +0000344 {'a', 'r', 'b', 'c', 'd'}
Georg Brandl116aa622007-08-15 14:28:22 +0000345 >>> a - b # letters in a but not in b
Guido van Rossum0616b792007-08-31 03:25:11 +0000346 {'r', 'd', 'b'}
Georg Brandl116aa622007-08-15 14:28:22 +0000347 >>> a | b # letters in either a or b
Guido van Rossum0616b792007-08-31 03:25:11 +0000348 {'a', 'c', 'r', 'd', 'b', 'm', 'z', 'l'}
Georg Brandl116aa622007-08-15 14:28:22 +0000349 >>> a & b # letters in both a and b
Guido van Rossum0616b792007-08-31 03:25:11 +0000350 {'a', 'c'}
Georg Brandl116aa622007-08-15 14:28:22 +0000351 >>> a ^ b # letters in a or b but not both
Guido van Rossum0616b792007-08-31 03:25:11 +0000352 {'r', 'd', 'b', 'm', 'z', 'l'}
353
354
Georg Brandl116aa622007-08-15 14:28:22 +0000355
356
357.. _tut-dictionaries:
358
359Dictionaries
360============
361
362Another useful data type built into Python is the *dictionary* (see
363:ref:`typesmapping`). Dictionaries are sometimes found in other languages as
364"associative memories" or "associative arrays". Unlike sequences, which are
365indexed by a range of numbers, dictionaries are indexed by *keys*, which can be
366any immutable type; strings and numbers can always be keys. Tuples can be used
367as keys if they contain only strings, numbers, or tuples; if a tuple contains
368any mutable object either directly or indirectly, it cannot be used as a key.
369You can't use lists as keys, since lists can be modified in place using index
370assignments, slice assignments, or methods like :meth:`append` and
371:meth:`extend`.
372
373It is best to think of a dictionary as an unordered set of *key: value* pairs,
374with the requirement that the keys are unique (within one dictionary). A pair of
375braces creates an empty dictionary: ``{}``. Placing a comma-separated list of
376key:value pairs within the braces adds initial key:value pairs to the
377dictionary; this is also the way dictionaries are written on output.
378
379The main operations on a dictionary are storing a value with some key and
380extracting the value given the key. It is also possible to delete a key:value
381pair with ``del``. If you store using a key that is already in use, the old
382value associated with that key is forgotten. It is an error to extract a value
383using a non-existent key.
384
385The :meth:`keys` method of a dictionary object returns a list of all the keys
386used in the dictionary, in arbitrary order (if you want it sorted, just apply
387the :meth:`sort` method to the list of keys). To check whether a single key is
Collin Winter19ab2bd2007-09-10 00:20:46 +0000388in the dictionary, use the :keyword:`in` keyword.
Georg Brandl116aa622007-08-15 14:28:22 +0000389
390Here is a small example using a dictionary::
391
392 >>> tel = {'jack': 4098, 'sape': 4139}
393 >>> tel['guido'] = 4127
394 >>> tel
395 {'sape': 4139, 'guido': 4127, 'jack': 4098}
396 >>> tel['jack']
397 4098
398 >>> del tel['sape']
399 >>> tel['irv'] = 4127
400 >>> tel
401 {'guido': 4127, 'irv': 4127, 'jack': 4098}
Neal Norwitze0906d12007-08-31 03:46:28 +0000402 >>> list(tel.keys())
Georg Brandl116aa622007-08-15 14:28:22 +0000403 ['guido', 'irv', 'jack']
Georg Brandl116aa622007-08-15 14:28:22 +0000404 >>> 'guido' in tel
405 True
Neal Norwitze0906d12007-08-31 03:46:28 +0000406 >>> 'jack' not in tel
407 False
Georg Brandl116aa622007-08-15 14:28:22 +0000408
409The :func:`dict` constructor builds dictionaries directly from lists of
410key-value pairs stored as tuples. When the pairs form a pattern, list
411comprehensions can compactly specify the key-value list. ::
412
413 >>> dict([('sape', 4139), ('guido', 4127), ('jack', 4098)])
414 {'sape': 4139, 'jack': 4098, 'guido': 4127}
415 >>> dict([(x, x**2) for x in (2, 4, 6)]) # use a list comprehension
416 {2: 4, 4: 16, 6: 36}
417
418Later in the tutorial, we will learn about Generator Expressions which are even
419better suited for the task of supplying key-values pairs to the :func:`dict`
420constructor.
421
422When the keys are simple strings, it is sometimes easier to specify pairs using
423keyword arguments::
424
425 >>> dict(sape=4139, guido=4127, jack=4098)
426 {'sape': 4139, 'jack': 4098, 'guido': 4127}
427
428
429.. _tut-loopidioms:
Guido van Rossum0616b792007-08-31 03:25:11 +0000430.. %
431 Find out the right way to do these DUBOIS
Georg Brandl116aa622007-08-15 14:28:22 +0000432
433Looping Techniques
434==================
435
436When looping through dictionaries, the key and corresponding value can be
Neal Norwitze0906d12007-08-31 03:46:28 +0000437retrieved at the same time using the :meth:`items` method. ::
Georg Brandl116aa622007-08-15 14:28:22 +0000438
439 >>> knights = {'gallahad': 'the pure', 'robin': 'the brave'}
Neal Norwitze0906d12007-08-31 03:46:28 +0000440 >>> for k, v in knights.items():
Guido van Rossum0616b792007-08-31 03:25:11 +0000441 ... print(k, v)
Georg Brandl116aa622007-08-15 14:28:22 +0000442 ...
443 gallahad the pure
444 robin the brave
445
446When looping through a sequence, the position index and corresponding value can
447be retrieved at the same time using the :func:`enumerate` function. ::
448
449 >>> for i, v in enumerate(['tic', 'tac', 'toe']):
Guido van Rossum0616b792007-08-31 03:25:11 +0000450 ... print(i, v)
Georg Brandl116aa622007-08-15 14:28:22 +0000451 ...
452 0 tic
453 1 tac
454 2 toe
455
456To loop over two or more sequences at the same time, the entries can be paired
457with the :func:`zip` function. ::
458
459 >>> questions = ['name', 'quest', 'favorite color']
460 >>> answers = ['lancelot', 'the holy grail', 'blue']
461 >>> for q, a in zip(questions, answers):
Guido van Rossum0616b792007-08-31 03:25:11 +0000462 ... print('What is your %s? It is %s.' % (q, a))
Georg Brandl116aa622007-08-15 14:28:22 +0000463 ...
464 What is your name? It is lancelot.
465 What is your quest? It is the holy grail.
466 What is your favorite color? It is blue.
467
468To loop over a sequence in reverse, first specify the sequence in a forward
469direction and then call the :func:`reversed` function. ::
470
Georg Brandle4ac7502007-09-03 07:10:24 +0000471 >>> for i in reversed(range(1, 10, 2)):
Guido van Rossum0616b792007-08-31 03:25:11 +0000472 ... print(i)
Georg Brandl116aa622007-08-15 14:28:22 +0000473 ...
474 9
475 7
476 5
477 3
478 1
479
480To loop over a sequence in sorted order, use the :func:`sorted` function which
481returns a new sorted list while leaving the source unaltered. ::
482
483 >>> basket = ['apple', 'orange', 'apple', 'pear', 'orange', 'banana']
484 >>> for f in sorted(set(basket)):
Guido van Rossum0616b792007-08-31 03:25:11 +0000485 ... print(f)
Georg Brandl116aa622007-08-15 14:28:22 +0000486 ...
487 apple
488 banana
489 orange
490 pear
491
492
493.. _tut-conditions:
494
495More on Conditions
496==================
497
498The conditions used in ``while`` and ``if`` statements can contain any
499operators, not just comparisons.
500
501The comparison operators ``in`` and ``not in`` check whether a value occurs
502(does not occur) in a sequence. The operators ``is`` and ``is not`` compare
503whether two objects are really the same object; this only matters for mutable
504objects like lists. All comparison operators have the same priority, which is
505lower than that of all numerical operators.
506
507Comparisons can be chained. For example, ``a < b == c`` tests whether ``a`` is
508less than ``b`` and moreover ``b`` equals ``c``.
509
510Comparisons may be combined using the Boolean operators ``and`` and ``or``, and
511the outcome of a comparison (or of any other Boolean expression) may be negated
512with ``not``. These have lower priorities than comparison operators; between
513them, ``not`` has the highest priority and ``or`` the lowest, so that ``A and
514not B or C`` is equivalent to ``(A and (not B)) or C``. As always, parentheses
515can be used to express the desired composition.
516
517The Boolean operators ``and`` and ``or`` are so-called *short-circuit*
518operators: their arguments are evaluated from left to right, and evaluation
519stops as soon as the outcome is determined. For example, if ``A`` and ``C`` are
520true but ``B`` is false, ``A and B and C`` does not evaluate the expression
521``C``. When used as a general value and not as a Boolean, the return value of a
522short-circuit operator is the last evaluated argument.
523
524It is possible to assign the result of a comparison or other Boolean expression
525to a variable. For example, ::
526
527 >>> string1, string2, string3 = '', 'Trondheim', 'Hammer Dance'
528 >>> non_null = string1 or string2 or string3
529 >>> non_null
530 'Trondheim'
531
532Note that in Python, unlike C, assignment cannot occur inside expressions. C
533programmers may grumble about this, but it avoids a common class of problems
534encountered in C programs: typing ``=`` in an expression when ``==`` was
535intended.
536
537
538.. _tut-comparing:
539
540Comparing Sequences and Other Types
541===================================
542
543Sequence objects may be compared to other objects with the same sequence type.
544The comparison uses *lexicographical* ordering: first the first two items are
545compared, and if they differ this determines the outcome of the comparison; if
546they are equal, the next two items are compared, and so on, until either
547sequence is exhausted. If two items to be compared are themselves sequences of
548the same type, the lexicographical comparison is carried out recursively. If
549all items of two sequences compare equal, the sequences are considered equal.
550If one sequence is an initial sub-sequence of the other, the shorter sequence is
551the smaller (lesser) one. Lexicographical ordering for strings uses the ASCII
552ordering for individual characters. Some examples of comparisons between
553sequences of the same type::
554
555 (1, 2, 3) < (1, 2, 4)
556 [1, 2, 3] < [1, 2, 4]
557 'ABC' < 'C' < 'Pascal' < 'Python'
558 (1, 2, 3, 4) < (1, 2, 4)
559 (1, 2) < (1, 2, -1)
560 (1, 2, 3) == (1.0, 2.0, 3.0)
561 (1, 2, ('aa', 'ab')) < (1, 2, ('abc', 'a'), 4)
562
Georg Brandl9f2c39a2007-10-08 14:08:36 +0000563Note that comparing objects of different types with ``<`` or ``>`` is legal
564provided that the objects have appropriate comparison methods. For example,
565mixed numeric types are compared according to their numeric value, so 0 equals
5660.0, etc. Otherwise, rather than providing an arbitrary ordering, the
567interpreter will raise a :exc:`TypeError` exception.