blob: 20bade5b15780d7d9c07b53c8c5ed496807a62ae [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
237 >>> [[x,x**2] for x in vec]
238 [[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
246Using the if-clause we can filter the stream::
247
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
263Here are some nested for's and other fancy behavior::
264
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
276 >>> [str(round(355/113.0, i)) for i in range(1,6)]
277 ['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
388in the dictionary, either use the dictionary's :meth:`has_key` method or the
389:keyword:`in` keyword.
390
391Here is a small example using a dictionary::
392
393 >>> tel = {'jack': 4098, 'sape': 4139}
394 >>> tel['guido'] = 4127
395 >>> tel
396 {'sape': 4139, 'guido': 4127, 'jack': 4098}
397 >>> tel['jack']
398 4098
399 >>> del tel['sape']
400 >>> tel['irv'] = 4127
401 >>> tel
402 {'guido': 4127, 'irv': 4127, 'jack': 4098}
Neal Norwitze0906d12007-08-31 03:46:28 +0000403 >>> list(tel.keys())
Georg Brandl116aa622007-08-15 14:28:22 +0000404 ['guido', 'irv', 'jack']
Georg Brandl116aa622007-08-15 14:28:22 +0000405 >>> 'guido' in tel
406 True
Neal Norwitze0906d12007-08-31 03:46:28 +0000407 >>> 'jack' not in tel
408 False
Georg Brandl116aa622007-08-15 14:28:22 +0000409
410The :func:`dict` constructor builds dictionaries directly from lists of
411key-value pairs stored as tuples. When the pairs form a pattern, list
412comprehensions can compactly specify the key-value list. ::
413
414 >>> dict([('sape', 4139), ('guido', 4127), ('jack', 4098)])
415 {'sape': 4139, 'jack': 4098, 'guido': 4127}
416 >>> dict([(x, x**2) for x in (2, 4, 6)]) # use a list comprehension
417 {2: 4, 4: 16, 6: 36}
418
419Later in the tutorial, we will learn about Generator Expressions which are even
420better suited for the task of supplying key-values pairs to the :func:`dict`
421constructor.
422
423When the keys are simple strings, it is sometimes easier to specify pairs using
424keyword arguments::
425
426 >>> dict(sape=4139, guido=4127, jack=4098)
427 {'sape': 4139, 'jack': 4098, 'guido': 4127}
428
429
430.. _tut-loopidioms:
Guido van Rossum0616b792007-08-31 03:25:11 +0000431.. %
432 Find out the right way to do these DUBOIS
Georg Brandl116aa622007-08-15 14:28:22 +0000433
434Looping Techniques
435==================
436
437When looping through dictionaries, the key and corresponding value can be
Neal Norwitze0906d12007-08-31 03:46:28 +0000438retrieved at the same time using the :meth:`items` method. ::
Georg Brandl116aa622007-08-15 14:28:22 +0000439
440 >>> knights = {'gallahad': 'the pure', 'robin': 'the brave'}
Neal Norwitze0906d12007-08-31 03:46:28 +0000441 >>> for k, v in knights.items():
Guido van Rossum0616b792007-08-31 03:25:11 +0000442 ... print(k, v)
Georg Brandl116aa622007-08-15 14:28:22 +0000443 ...
444 gallahad the pure
445 robin the brave
446
447When looping through a sequence, the position index and corresponding value can
448be retrieved at the same time using the :func:`enumerate` function. ::
449
450 >>> for i, v in enumerate(['tic', 'tac', 'toe']):
Guido van Rossum0616b792007-08-31 03:25:11 +0000451 ... print(i, v)
Georg Brandl116aa622007-08-15 14:28:22 +0000452 ...
453 0 tic
454 1 tac
455 2 toe
456
457To loop over two or more sequences at the same time, the entries can be paired
458with the :func:`zip` function. ::
459
460 >>> questions = ['name', 'quest', 'favorite color']
461 >>> answers = ['lancelot', 'the holy grail', 'blue']
462 >>> for q, a in zip(questions, answers):
Guido van Rossum0616b792007-08-31 03:25:11 +0000463 ... print('What is your %s? It is %s.' % (q, a))
Georg Brandl116aa622007-08-15 14:28:22 +0000464 ...
465 What is your name? It is lancelot.
466 What is your quest? It is the holy grail.
467 What is your favorite color? It is blue.
468
469To loop over a sequence in reverse, first specify the sequence in a forward
470direction and then call the :func:`reversed` function. ::
471
472 >>> for i in reversed(range(1,10,2)):
Guido van Rossum0616b792007-08-31 03:25:11 +0000473 ... print(i)
Georg Brandl116aa622007-08-15 14:28:22 +0000474 ...
475 9
476 7
477 5
478 3
479 1
480
481To loop over a sequence in sorted order, use the :func:`sorted` function which
482returns a new sorted list while leaving the source unaltered. ::
483
484 >>> basket = ['apple', 'orange', 'apple', 'pear', 'orange', 'banana']
485 >>> for f in sorted(set(basket)):
Guido van Rossum0616b792007-08-31 03:25:11 +0000486 ... print(f)
Georg Brandl116aa622007-08-15 14:28:22 +0000487 ...
488 apple
489 banana
490 orange
491 pear
492
493
494.. _tut-conditions:
495
496More on Conditions
497==================
498
499The conditions used in ``while`` and ``if`` statements can contain any
500operators, not just comparisons.
501
502The comparison operators ``in`` and ``not in`` check whether a value occurs
503(does not occur) in a sequence. The operators ``is`` and ``is not`` compare
504whether two objects are really the same object; this only matters for mutable
505objects like lists. All comparison operators have the same priority, which is
506lower than that of all numerical operators.
507
508Comparisons can be chained. For example, ``a < b == c`` tests whether ``a`` is
509less than ``b`` and moreover ``b`` equals ``c``.
510
511Comparisons may be combined using the Boolean operators ``and`` and ``or``, and
512the outcome of a comparison (or of any other Boolean expression) may be negated
513with ``not``. These have lower priorities than comparison operators; between
514them, ``not`` has the highest priority and ``or`` the lowest, so that ``A and
515not B or C`` is equivalent to ``(A and (not B)) or C``. As always, parentheses
516can be used to express the desired composition.
517
518The Boolean operators ``and`` and ``or`` are so-called *short-circuit*
519operators: their arguments are evaluated from left to right, and evaluation
520stops as soon as the outcome is determined. For example, if ``A`` and ``C`` are
521true but ``B`` is false, ``A and B and C`` does not evaluate the expression
522``C``. When used as a general value and not as a Boolean, the return value of a
523short-circuit operator is the last evaluated argument.
524
525It is possible to assign the result of a comparison or other Boolean expression
526to a variable. For example, ::
527
528 >>> string1, string2, string3 = '', 'Trondheim', 'Hammer Dance'
529 >>> non_null = string1 or string2 or string3
530 >>> non_null
531 'Trondheim'
532
533Note that in Python, unlike C, assignment cannot occur inside expressions. C
534programmers may grumble about this, but it avoids a common class of problems
535encountered in C programs: typing ``=`` in an expression when ``==`` was
536intended.
537
538
539.. _tut-comparing:
540
541Comparing Sequences and Other Types
542===================================
543
544Sequence objects may be compared to other objects with the same sequence type.
545The comparison uses *lexicographical* ordering: first the first two items are
546compared, and if they differ this determines the outcome of the comparison; if
547they are equal, the next two items are compared, and so on, until either
548sequence is exhausted. If two items to be compared are themselves sequences of
549the same type, the lexicographical comparison is carried out recursively. If
550all items of two sequences compare equal, the sequences are considered equal.
551If one sequence is an initial sub-sequence of the other, the shorter sequence is
552the smaller (lesser) one. Lexicographical ordering for strings uses the ASCII
553ordering for individual characters. Some examples of comparisons between
554sequences of the same type::
555
556 (1, 2, 3) < (1, 2, 4)
557 [1, 2, 3] < [1, 2, 4]
558 'ABC' < 'C' < 'Pascal' < 'Python'
559 (1, 2, 3, 4) < (1, 2, 4)
560 (1, 2) < (1, 2, -1)
561 (1, 2, 3) == (1.0, 2.0, 3.0)
562 (1, 2, ('aa', 'ab')) < (1, 2, ('abc', 'a'), 4)
563
564Note that comparing objects of different types is legal. The outcome is
565deterministic but arbitrary: the types are ordered by their name. Thus, a list
566is always smaller than a string, a string is always smaller than a tuple, etc.
567[#]_ Mixed numeric types are compared according to their numeric value, so 0
568equals 0.0, etc.
569
570
571.. rubric:: Footnotes
572
573.. [#] The rules for comparing objects of different types should not be relied upon;
574 they may change in a future version of the language.
575