summaryrefslogtreecommitdiff
path: root/devdocs/python~3.12/library%2Fcollections.html
blob: 345017f6be036f8b51cc7f4b8431acb622ec5a44 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
 <span id="collections-container-datatypes"></span><h1>collections — Container datatypes</h1> <p><strong>Source code:</strong> <a class="reference external" href="https://github.com/python/cpython/tree/3.12/Lib/collections/__init__.py">Lib/collections/__init__.py</a></p>  <p>This module implements specialized container datatypes providing alternatives to Python’s general purpose built-in containers, <a class="reference internal" href="stdtypes#dict" title="dict"><code>dict</code></a>, <a class="reference internal" href="stdtypes#list" title="list"><code>list</code></a>, <a class="reference internal" href="stdtypes#set" title="set"><code>set</code></a>, and <a class="reference internal" href="stdtypes#tuple" title="tuple"><code>tuple</code></a>.</p> <table class="docutils align-default">   <tr>
<td><p><a class="reference internal" href="#collections.namedtuple" title="collections.namedtuple"><code>namedtuple()</code></a></p></td> <td><p>factory function for creating tuple subclasses with named fields</p></td> </tr> <tr>
<td><p><a class="reference internal" href="#collections.deque" title="collections.deque"><code>deque</code></a></p></td> <td><p>list-like container with fast appends and pops on either end</p></td> </tr> <tr>
<td><p><a class="reference internal" href="#collections.ChainMap" title="collections.ChainMap"><code>ChainMap</code></a></p></td> <td><p>dict-like class for creating a single view of multiple mappings</p></td> </tr> <tr>
<td><p><a class="reference internal" href="#collections.Counter" title="collections.Counter"><code>Counter</code></a></p></td> <td><p>dict subclass for counting <a class="reference internal" href="../glossary#term-hashable"><span class="xref std std-term">hashable</span></a> objects</p></td> </tr> <tr>
<td><p><a class="reference internal" href="#collections.OrderedDict" title="collections.OrderedDict"><code>OrderedDict</code></a></p></td> <td><p>dict subclass that remembers the order entries were added</p></td> </tr> <tr>
<td><p><a class="reference internal" href="#collections.defaultdict" title="collections.defaultdict"><code>defaultdict</code></a></p></td> <td><p>dict subclass that calls a factory function to supply missing values</p></td> </tr> <tr>
<td><p><a class="reference internal" href="#collections.UserDict" title="collections.UserDict"><code>UserDict</code></a></p></td> <td><p>wrapper around dictionary objects for easier dict subclassing</p></td> </tr> <tr>
<td><p><a class="reference internal" href="#collections.UserList" title="collections.UserList"><code>UserList</code></a></p></td> <td><p>wrapper around list objects for easier list subclassing</p></td> </tr> <tr>
<td><p><a class="reference internal" href="#collections.UserString" title="collections.UserString"><code>UserString</code></a></p></td> <td><p>wrapper around string objects for easier string subclassing</p></td> </tr>  </table> <section id="chainmap-objects"> <h2>ChainMap objects</h2> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.3.</span></p> </div> <p>A <a class="reference internal" href="#collections.ChainMap" title="collections.ChainMap"><code>ChainMap</code></a> class is provided for quickly linking a number of mappings so they can be treated as a single unit. It is often much faster than creating a new dictionary and running multiple <a class="reference internal" href="stdtypes#dict.update" title="dict.update"><code>update()</code></a> calls.</p> <p>The class can be used to simulate nested scopes and is useful in templating.</p> <dl class="py class"> <dt class="sig sig-object py" id="collections.ChainMap">
<code>class collections.ChainMap(*maps)</code> </dt> <dd>
<p>A <a class="reference internal" href="#collections.ChainMap" title="collections.ChainMap"><code>ChainMap</code></a> groups multiple dicts or other mappings together to create a single, updateable view. If no <em>maps</em> are specified, a single empty dictionary is provided so that a new chain always has at least one mapping.</p> <p>The underlying mappings are stored in a list. That list is public and can be accessed or updated using the <em>maps</em> attribute. There is no other state.</p> <p>Lookups search the underlying mappings successively until a key is found. In contrast, writes, updates, and deletions only operate on the first mapping.</p> <p>A <a class="reference internal" href="#collections.ChainMap" title="collections.ChainMap"><code>ChainMap</code></a> incorporates the underlying mappings by reference. So, if one of the underlying mappings gets updated, those changes will be reflected in <a class="reference internal" href="#collections.ChainMap" title="collections.ChainMap"><code>ChainMap</code></a>.</p> <p>All of the usual dictionary methods are supported. In addition, there is a <em>maps</em> attribute, a method for creating new subcontexts, and a property for accessing all but the first mapping:</p> <dl class="py attribute"> <dt class="sig sig-object py" id="collections.ChainMap.maps">
<code>maps</code> </dt> <dd>
<p>A user updateable list of mappings. The list is ordered from first-searched to last-searched. It is the only stored state and can be modified to change which mappings are searched. The list should always contain at least one mapping.</p> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="collections.ChainMap.new_child">
<code>new_child(m=None, **kwargs)</code> </dt> <dd>
<p>Returns a new <a class="reference internal" href="#collections.ChainMap" title="collections.ChainMap"><code>ChainMap</code></a> containing a new map followed by all of the maps in the current instance. If <code>m</code> is specified, it becomes the new map at the front of the list of mappings; if not specified, an empty dict is used, so that a call to <code>d.new_child()</code> is equivalent to: <code>ChainMap({}, *d.maps)</code>. If any keyword arguments are specified, they update passed map or new empty dict. This method is used for creating subcontexts that can be updated without altering values in any of the parent mappings.</p> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.4: </span>The optional <code>m</code> parameter was added.</p> </div> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.10: </span>Keyword arguments support was added.</p> </div> </dd>
</dl> <dl class="py attribute"> <dt class="sig sig-object py" id="collections.ChainMap.parents">
<code>parents</code> </dt> <dd>
<p>Property returning a new <a class="reference internal" href="#collections.ChainMap" title="collections.ChainMap"><code>ChainMap</code></a> containing all of the maps in the current instance except the first one. This is useful for skipping the first map in the search. Use cases are similar to those for the <a class="reference internal" href="../reference/simple_stmts#nonlocal"><code>nonlocal</code></a> keyword used in <a class="reference internal" href="../glossary#term-nested-scope"><span class="xref std std-term">nested scopes</span></a>. The use cases also parallel those for the built-in <a class="reference internal" href="functions#super" title="super"><code>super()</code></a> function. A reference to <code>d.parents</code> is equivalent to: <code>ChainMap(*d.maps[1:])</code>.</p> </dd>
</dl> <p>Note, the iteration order of a <a class="reference internal" href="#collections.ChainMap" title="collections.ChainMap"><code>ChainMap()</code></a> is determined by scanning the mappings last to first:</p> <pre data-language="python">&gt;&gt;&gt; baseline = {'music': 'bach', 'art': 'rembrandt'}
&gt;&gt;&gt; adjustments = {'art': 'van gogh', 'opera': 'carmen'}
&gt;&gt;&gt; list(ChainMap(adjustments, baseline))
['music', 'art', 'opera']
</pre> <p>This gives the same ordering as a series of <a class="reference internal" href="stdtypes#dict.update" title="dict.update"><code>dict.update()</code></a> calls starting with the last mapping:</p> <pre data-language="python">&gt;&gt;&gt; combined = baseline.copy()
&gt;&gt;&gt; combined.update(adjustments)
&gt;&gt;&gt; list(combined)
['music', 'art', 'opera']
</pre> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.9: </span>Added support for <code>|</code> and <code>|=</code> operators, specified in <span class="target" id="index-0"></span><a class="pep reference external" href="https://peps.python.org/pep-0584/"><strong>PEP 584</strong></a>.</p> </div> </dd>
</dl> <div class="admonition seealso"> <p class="admonition-title">See also</p> <ul class="simple"> <li>The <a class="reference external" href="https://github.com/enthought/codetools/blob/4.0.0/codetools/contexts/multi_context.py">MultiContext class</a> in the Enthought <a class="reference external" href="https://github.com/enthought/codetools">CodeTools package</a> has options to support writing to any mapping in the chain.</li> <li>Django’s <a class="reference external" href="https://github.com/django/django/blob/main/django/template/context.py">Context class</a> for templating is a read-only chain of mappings. It also features pushing and popping of contexts similar to the <a class="reference internal" href="#collections.ChainMap.new_child" title="collections.ChainMap.new_child"><code>new_child()</code></a> method and the <a class="reference internal" href="#collections.ChainMap.parents" title="collections.ChainMap.parents"><code>parents</code></a> property.</li> <li>The <a class="reference external" href="https://code.activestate.com/recipes/577434/">Nested Contexts recipe</a> has options to control whether writes and other mutations apply only to the first mapping or to any mapping in the chain.</li> <li>A <a class="reference external" href="https://code.activestate.com/recipes/305268/">greatly simplified read-only version of Chainmap</a>.</li> </ul> </div> <section id="chainmap-examples-and-recipes"> <h3>
<a class="reference internal" href="#collections.ChainMap" title="collections.ChainMap"><code>ChainMap</code></a> Examples and Recipes</h3> <p>This section shows various approaches to working with chained maps.</p> <p>Example of simulating Python’s internal lookup chain:</p> <pre data-language="python">import builtins
pylookup = ChainMap(locals(), globals(), vars(builtins))
</pre> <p>Example of letting user specified command-line arguments take precedence over environment variables which in turn take precedence over default values:</p> <pre data-language="python">import os, argparse

defaults = {'color': 'red', 'user': 'guest'}

parser = argparse.ArgumentParser()
parser.add_argument('-u', '--user')
parser.add_argument('-c', '--color')
namespace = parser.parse_args()
command_line_args = {k: v for k, v in vars(namespace).items() if v is not None}

combined = ChainMap(command_line_args, os.environ, defaults)
print(combined['color'])
print(combined['user'])
</pre> <p>Example patterns for using the <a class="reference internal" href="#collections.ChainMap" title="collections.ChainMap"><code>ChainMap</code></a> class to simulate nested contexts:</p> <pre data-language="python">c = ChainMap()        # Create root context
d = c.new_child()     # Create nested child context
e = c.new_child()     # Child of c, independent from d
e.maps[0]             # Current context dictionary -- like Python's locals()
e.maps[-1]            # Root context -- like Python's globals()
e.parents             # Enclosing context chain -- like Python's nonlocals

d['x'] = 1            # Set value in current context
d['x']                # Get first key in the chain of contexts
del d['x']            # Delete from current context
list(d)               # All nested values
k in d                # Check all nested values
len(d)                # Number of nested values
d.items()             # All nested items
dict(d)               # Flatten into a regular dictionary
</pre> <p>The <a class="reference internal" href="#collections.ChainMap" title="collections.ChainMap"><code>ChainMap</code></a> class only makes updates (writes and deletions) to the first mapping in the chain while lookups will search the full chain. However, if deep writes and deletions are desired, it is easy to make a subclass that updates keys found deeper in the chain:</p> <pre data-language="python">class DeepChainMap(ChainMap):
    'Variant of ChainMap that allows direct updates to inner scopes'

    def __setitem__(self, key, value):
        for mapping in self.maps:
            if key in mapping:
                mapping[key] = value
                return
        self.maps[0][key] = value

    def __delitem__(self, key):
        for mapping in self.maps:
            if key in mapping:
                del mapping[key]
                return
        raise KeyError(key)

&gt;&gt;&gt; d = DeepChainMap({'zebra': 'black'}, {'elephant': 'blue'}, {'lion': 'yellow'})
&gt;&gt;&gt; d['lion'] = 'orange'         # update an existing key two levels down
&gt;&gt;&gt; d['snake'] = 'red'           # new keys get added to the topmost dict
&gt;&gt;&gt; del d['elephant']            # remove an existing key one level down
&gt;&gt;&gt; d                            # display result
DeepChainMap({'zebra': 'black', 'snake': 'red'}, {}, {'lion': 'orange'})
</pre> </section> </section> <section id="counter-objects"> <h2>Counter objects</h2> <p>A counter tool is provided to support convenient and rapid tallies. For example:</p> <pre data-language="python">&gt;&gt;&gt; # Tally occurrences of words in a list
&gt;&gt;&gt; cnt = Counter()
&gt;&gt;&gt; for word in ['red', 'blue', 'red', 'green', 'blue', 'blue']:
...     cnt[word] += 1
...
&gt;&gt;&gt; cnt
Counter({'blue': 3, 'red': 2, 'green': 1})

&gt;&gt;&gt; # Find the ten most common words in Hamlet
&gt;&gt;&gt; import re
&gt;&gt;&gt; words = re.findall(r'\w+', open('hamlet.txt').read().lower())
&gt;&gt;&gt; Counter(words).most_common(10)
[('the', 1143), ('and', 966), ('to', 762), ('of', 669), ('i', 631),
 ('you', 554),  ('a', 546), ('my', 514), ('hamlet', 471), ('in', 451)]
</pre> <dl class="py class"> <dt class="sig sig-object py" id="collections.Counter">
<code>class collections.Counter([iterable-or-mapping])</code> </dt> <dd>
<p>A <a class="reference internal" href="#collections.Counter" title="collections.Counter"><code>Counter</code></a> is a <a class="reference internal" href="stdtypes#dict" title="dict"><code>dict</code></a> subclass for counting <a class="reference internal" href="../glossary#term-hashable"><span class="xref std std-term">hashable</span></a> objects. It is a collection where elements are stored as dictionary keys and their counts are stored as dictionary values. Counts are allowed to be any integer value including zero or negative counts. The <a class="reference internal" href="#collections.Counter" title="collections.Counter"><code>Counter</code></a> class is similar to bags or multisets in other languages.</p> <p>Elements are counted from an <em>iterable</em> or initialized from another <em>mapping</em> (or counter):</p> <pre data-language="python">&gt;&gt;&gt; c = Counter()                           # a new, empty counter
&gt;&gt;&gt; c = Counter('gallahad')                 # a new counter from an iterable
&gt;&gt;&gt; c = Counter({'red': 4, 'blue': 2})      # a new counter from a mapping
&gt;&gt;&gt; c = Counter(cats=4, dogs=8)             # a new counter from keyword args
</pre> <p>Counter objects have a dictionary interface except that they return a zero count for missing items instead of raising a <a class="reference internal" href="exceptions#KeyError" title="KeyError"><code>KeyError</code></a>:</p> <pre data-language="python">&gt;&gt;&gt; c = Counter(['eggs', 'ham'])
&gt;&gt;&gt; c['bacon']                              # count of a missing element is zero
0
</pre> <p>Setting a count to zero does not remove an element from a counter. Use <code>del</code> to remove it entirely:</p> <pre data-language="python">&gt;&gt;&gt; c['sausage'] = 0                        # counter entry with a zero count
&gt;&gt;&gt; del c['sausage']                        # del actually removes the entry
</pre> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.1.</span></p> </div> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.7: </span>As a <a class="reference internal" href="stdtypes#dict" title="dict"><code>dict</code></a> subclass, <a class="reference internal" href="#collections.Counter" title="collections.Counter"><code>Counter</code></a> inherited the capability to remember insertion order. Math operations on <em>Counter</em> objects also preserve order. Results are ordered according to when an element is first encountered in the left operand and then by the order encountered in the right operand.</p> </div> <p>Counter objects support additional methods beyond those available for all dictionaries:</p> <dl class="py method"> <dt class="sig sig-object py" id="collections.Counter.elements">
<code>elements()</code> </dt> <dd>
<p>Return an iterator over elements repeating each as many times as its count. Elements are returned in the order first encountered. If an element’s count is less than one, <a class="reference internal" href="#collections.Counter.elements" title="collections.Counter.elements"><code>elements()</code></a> will ignore it.</p> <pre data-language="python">&gt;&gt;&gt; c = Counter(a=4, b=2, c=0, d=-2)
&gt;&gt;&gt; sorted(c.elements())
['a', 'a', 'a', 'a', 'b', 'b']
</pre> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="collections.Counter.most_common">
<code>most_common([n])</code> </dt> <dd>
<p>Return a list of the <em>n</em> most common elements and their counts from the most common to the least. If <em>n</em> is omitted or <code>None</code>, <a class="reference internal" href="#collections.Counter.most_common" title="collections.Counter.most_common"><code>most_common()</code></a> returns <em>all</em> elements in the counter. Elements with equal counts are ordered in the order first encountered:</p> <pre data-language="python">&gt;&gt;&gt; Counter('abracadabra').most_common(3)
[('a', 5), ('b', 2), ('r', 2)]
</pre> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="collections.Counter.subtract">
<code>subtract([iterable-or-mapping])</code> </dt> <dd>
<p>Elements are subtracted from an <em>iterable</em> or from another <em>mapping</em> (or counter). Like <a class="reference internal" href="stdtypes#dict.update" title="dict.update"><code>dict.update()</code></a> but subtracts counts instead of replacing them. Both inputs and outputs may be zero or negative.</p> <pre data-language="python">&gt;&gt;&gt; c = Counter(a=4, b=2, c=0, d=-2)
&gt;&gt;&gt; d = Counter(a=1, b=2, c=3, d=4)
&gt;&gt;&gt; c.subtract(d)
&gt;&gt;&gt; c
Counter({'a': 3, 'b': 0, 'c': -3, 'd': -6})
</pre> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.2.</span></p> </div> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="collections.Counter.total">
<code>total()</code> </dt> <dd>
<p>Compute the sum of the counts.</p> <pre data-language="python">&gt;&gt;&gt; c = Counter(a=10, b=5, c=0)
&gt;&gt;&gt; c.total()
15
</pre> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.10.</span></p> </div> </dd>
</dl> <p>The usual dictionary methods are available for <a class="reference internal" href="#collections.Counter" title="collections.Counter"><code>Counter</code></a> objects except for two which work differently for counters.</p> <dl class="py method"> <dt class="sig sig-object py" id="collections.Counter.fromkeys">
<code>fromkeys(iterable)</code> </dt> <dd>
<p>This class method is not implemented for <a class="reference internal" href="#collections.Counter" title="collections.Counter"><code>Counter</code></a> objects.</p> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="collections.Counter.update">
<code>update([iterable-or-mapping])</code> </dt> <dd>
<p>Elements are counted from an <em>iterable</em> or added-in from another <em>mapping</em> (or counter). Like <a class="reference internal" href="stdtypes#dict.update" title="dict.update"><code>dict.update()</code></a> but adds counts instead of replacing them. Also, the <em>iterable</em> is expected to be a sequence of elements, not a sequence of <code>(key, value)</code> pairs.</p> </dd>
</dl> </dd>
</dl> <p>Counters support rich comparison operators for equality, subset, and superset relationships: <code>==</code>, <code>!=</code>, <code>&lt;</code>, <code>&lt;=</code>, <code>&gt;</code>, <code>&gt;=</code>. All of those tests treat missing elements as having zero counts so that <code>Counter(a=1) == Counter(a=1, b=0)</code> returns true.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.10: </span>Rich comparison operations were added.</p> </div> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.10: </span>In equality tests, missing elements are treated as having zero counts. Formerly, <code>Counter(a=3)</code> and <code>Counter(a=3, b=0)</code> were considered distinct.</p> </div> <p>Common patterns for working with <a class="reference internal" href="#collections.Counter" title="collections.Counter"><code>Counter</code></a> objects:</p> <pre data-language="python">c.total()                       # total of all counts
c.clear()                       # reset all counts
list(c)                         # list unique elements
set(c)                          # convert to a set
dict(c)                         # convert to a regular dictionary
c.items()                       # convert to a list of (elem, cnt) pairs
Counter(dict(list_of_pairs))    # convert from a list of (elem, cnt) pairs
c.most_common()[:-n-1:-1]       # n least common elements
+c                              # remove zero and negative counts
</pre> <p>Several mathematical operations are provided for combining <a class="reference internal" href="#collections.Counter" title="collections.Counter"><code>Counter</code></a> objects to produce multisets (counters that have counts greater than zero). Addition and subtraction combine counters by adding or subtracting the counts of corresponding elements. Intersection and union return the minimum and maximum of corresponding counts. Equality and inclusion compare corresponding counts. Each operation can accept inputs with signed counts, but the output will exclude results with counts of zero or less.</p> <pre data-language="pycon3">&gt;&gt;&gt; c = Counter(a=3, b=1)
&gt;&gt;&gt; d = Counter(a=1, b=2)
&gt;&gt;&gt; c + d                       # add two counters together:  c[x] + d[x]
Counter({'a': 4, 'b': 3})
&gt;&gt;&gt; c - d                       # subtract (keeping only positive counts)
Counter({'a': 2})
&gt;&gt;&gt; c &amp; d                       # intersection:  min(c[x], d[x])
Counter({'a': 1, 'b': 1})
&gt;&gt;&gt; c | d                       # union:  max(c[x], d[x])
Counter({'a': 3, 'b': 2})
&gt;&gt;&gt; c == d                      # equality:  c[x] == d[x]
False
&gt;&gt;&gt; c &lt;= d                      # inclusion:  c[x] &lt;= d[x]
False
</pre> <p>Unary addition and subtraction are shortcuts for adding an empty counter or subtracting from an empty counter.</p> <pre data-language="python">&gt;&gt;&gt; c = Counter(a=2, b=-4)
&gt;&gt;&gt; +c
Counter({'a': 2})
&gt;&gt;&gt; -c
Counter({'b': 4})
</pre> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.3: </span>Added support for unary plus, unary minus, and in-place multiset operations.</p> </div> <div class="admonition note"> <p class="admonition-title">Note</p> <p>Counters were primarily designed to work with positive integers to represent running counts; however, care was taken to not unnecessarily preclude use cases needing other types or negative values. To help with those use cases, this section documents the minimum range and type restrictions.</p> <ul class="simple"> <li>The <a class="reference internal" href="#collections.Counter" title="collections.Counter"><code>Counter</code></a> class itself is a dictionary subclass with no restrictions on its keys and values. The values are intended to be numbers representing counts, but you <em>could</em> store anything in the value field.</li> <li>The <a class="reference internal" href="#collections.Counter.most_common" title="collections.Counter.most_common"><code>most_common()</code></a> method requires only that the values be orderable.</li> <li>For in-place operations such as <code>c[key] += 1</code>, the value type need only support addition and subtraction. So fractions, floats, and decimals would work and negative values are supported. The same is also true for <a class="reference internal" href="#collections.Counter.update" title="collections.Counter.update"><code>update()</code></a> and <a class="reference internal" href="#collections.Counter.subtract" title="collections.Counter.subtract"><code>subtract()</code></a> which allow negative and zero values for both inputs and outputs.</li> <li>The multiset methods are designed only for use cases with positive values. The inputs may be negative or zero, but only outputs with positive values are created. There are no type restrictions, but the value type needs to support addition, subtraction, and comparison.</li> <li>The <a class="reference internal" href="#collections.Counter.elements" title="collections.Counter.elements"><code>elements()</code></a> method requires integer counts. It ignores zero and negative counts.</li> </ul> </div> <div class="admonition seealso"> <p class="admonition-title">See also</p> <ul> <li>
<a class="reference external" href="https://www.gnu.org/software/smalltalk/manual-base/html_node/Bag.html">Bag class</a> in Smalltalk.</li> <li>Wikipedia entry for <a class="reference external" href="https://en.wikipedia.org/wiki/Multiset">Multisets</a>.</li> <li>
<a class="reference external" href="http://www.java2s.com/Tutorial/Cpp/0380__set-multiset/Catalog0380__set-multiset.htm">C++ multisets</a> tutorial with examples.</li> <li>For mathematical operations on multisets and their use cases, see <em>Knuth, Donald. The Art of Computer Programming Volume II, Section 4.6.3, Exercise 19</em>.</li> <li>
<p>To enumerate all distinct multisets of a given size over a given set of elements, see <a class="reference internal" href="itertools#itertools.combinations_with_replacement" title="itertools.combinations_with_replacement"><code>itertools.combinations_with_replacement()</code></a>:</p> <pre data-language="python">map(Counter, combinations_with_replacement('ABC', 2)) # --&gt; AA AB AC BB BC CC
</pre> </li> </ul> </div> </section> <section id="deque-objects"> <h2>deque objects</h2> <dl class="py class"> <dt class="sig sig-object py" id="collections.deque">
<code>class collections.deque([iterable[, maxlen]])</code> </dt> <dd>
<p>Returns a new deque object initialized left-to-right (using <a class="reference internal" href="#collections.deque.append" title="collections.deque.append"><code>append()</code></a>) with data from <em>iterable</em>. If <em>iterable</em> is not specified, the new deque is empty.</p> <p>Deques are a generalization of stacks and queues (the name is pronounced “deck” and is short for “double-ended queue”). Deques support thread-safe, memory efficient appends and pops from either side of the deque with approximately the same O(1) performance in either direction.</p> <p>Though <a class="reference internal" href="stdtypes#list" title="list"><code>list</code></a> objects support similar operations, they are optimized for fast fixed-length operations and incur O(n) memory movement costs for <code>pop(0)</code> and <code>insert(0, v)</code> operations which change both the size and position of the underlying data representation.</p> <p>If <em>maxlen</em> is not specified or is <code>None</code>, deques may grow to an arbitrary length. Otherwise, the deque is bounded to the specified maximum length. Once a bounded length deque is full, when new items are added, a corresponding number of items are discarded from the opposite end. Bounded length deques provide functionality similar to the <code>tail</code> filter in Unix. They are also useful for tracking transactions and other pools of data where only the most recent activity is of interest.</p> <p>Deque objects support the following methods:</p> <dl class="py method"> <dt class="sig sig-object py" id="collections.deque.append">
<code>append(x)</code> </dt> <dd>
<p>Add <em>x</em> to the right side of the deque.</p> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="collections.deque.appendleft">
<code>appendleft(x)</code> </dt> <dd>
<p>Add <em>x</em> to the left side of the deque.</p> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="collections.deque.clear">
<code>clear()</code> </dt> <dd>
<p>Remove all elements from the deque leaving it with length 0.</p> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="collections.deque.copy">
<code>copy()</code> </dt> <dd>
<p>Create a shallow copy of the deque.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.5.</span></p> </div> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="collections.deque.count">
<code>count(x)</code> </dt> <dd>
<p>Count the number of deque elements equal to <em>x</em>.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.2.</span></p> </div> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="collections.deque.extend">
<code>extend(iterable)</code> </dt> <dd>
<p>Extend the right side of the deque by appending elements from the iterable argument.</p> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="collections.deque.extendleft">
<code>extendleft(iterable)</code> </dt> <dd>
<p>Extend the left side of the deque by appending elements from <em>iterable</em>. Note, the series of left appends results in reversing the order of elements in the iterable argument.</p> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="collections.deque.index">
<code>index(x[, start[, stop]])</code> </dt> <dd>
<p>Return the position of <em>x</em> in the deque (at or after index <em>start</em> and before index <em>stop</em>). Returns the first match or raises <a class="reference internal" href="exceptions#ValueError" title="ValueError"><code>ValueError</code></a> if not found.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.5.</span></p> </div> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="collections.deque.insert">
<code>insert(i, x)</code> </dt> <dd>
<p>Insert <em>x</em> into the deque at position <em>i</em>.</p> <p>If the insertion would cause a bounded deque to grow beyond <em>maxlen</em>, an <a class="reference internal" href="exceptions#IndexError" title="IndexError"><code>IndexError</code></a> is raised.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.5.</span></p> </div> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="collections.deque.pop">
<code>pop()</code> </dt> <dd>
<p>Remove and return an element from the right side of the deque. If no elements are present, raises an <a class="reference internal" href="exceptions#IndexError" title="IndexError"><code>IndexError</code></a>.</p> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="collections.deque.popleft">
<code>popleft()</code> </dt> <dd>
<p>Remove and return an element from the left side of the deque. If no elements are present, raises an <a class="reference internal" href="exceptions#IndexError" title="IndexError"><code>IndexError</code></a>.</p> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="collections.deque.remove">
<code>remove(value)</code> </dt> <dd>
<p>Remove the first occurrence of <em>value</em>. If not found, raises a <a class="reference internal" href="exceptions#ValueError" title="ValueError"><code>ValueError</code></a>.</p> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="collections.deque.reverse">
<code>reverse()</code> </dt> <dd>
<p>Reverse the elements of the deque in-place and then return <code>None</code>.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.2.</span></p> </div> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="collections.deque.rotate">
<code>rotate(n=1)</code> </dt> <dd>
<p>Rotate the deque <em>n</em> steps to the right. If <em>n</em> is negative, rotate to the left.</p> <p>When the deque is not empty, rotating one step to the right is equivalent to <code>d.appendleft(d.pop())</code>, and rotating one step to the left is equivalent to <code>d.append(d.popleft())</code>.</p> </dd>
</dl> <p>Deque objects also provide one read-only attribute:</p> <dl class="py attribute"> <dt class="sig sig-object py" id="collections.deque.maxlen">
<code>maxlen</code> </dt> <dd>
<p>Maximum size of a deque or <code>None</code> if unbounded.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.1.</span></p> </div> </dd>
</dl> </dd>
</dl> <p>In addition to the above, deques support iteration, pickling, <code>len(d)</code>, <code>reversed(d)</code>, <code>copy.copy(d)</code>, <code>copy.deepcopy(d)</code>, membership testing with the <a class="reference internal" href="../reference/expressions#in"><code>in</code></a> operator, and subscript references such as <code>d[0]</code> to access the first element. Indexed access is O(1) at both ends but slows to O(n) in the middle. For fast random access, use lists instead.</p> <p>Starting in version 3.5, deques support <code>__add__()</code>, <code>__mul__()</code>, and <code>__imul__()</code>.</p> <p>Example:</p> <pre data-language="pycon3">&gt;&gt;&gt; from collections import deque
&gt;&gt;&gt; d = deque('ghi')                 # make a new deque with three items
&gt;&gt;&gt; for elem in d:                   # iterate over the deque's elements
...     print(elem.upper())
G
H
I

&gt;&gt;&gt; d.append('j')                    # add a new entry to the right side
&gt;&gt;&gt; d.appendleft('f')                # add a new entry to the left side
&gt;&gt;&gt; d                                # show the representation of the deque
deque(['f', 'g', 'h', 'i', 'j'])

&gt;&gt;&gt; d.pop()                          # return and remove the rightmost item
'j'
&gt;&gt;&gt; d.popleft()                      # return and remove the leftmost item
'f'
&gt;&gt;&gt; list(d)                          # list the contents of the deque
['g', 'h', 'i']
&gt;&gt;&gt; d[0]                             # peek at leftmost item
'g'
&gt;&gt;&gt; d[-1]                            # peek at rightmost item
'i'

&gt;&gt;&gt; list(reversed(d))                # list the contents of a deque in reverse
['i', 'h', 'g']
&gt;&gt;&gt; 'h' in d                         # search the deque
True
&gt;&gt;&gt; d.extend('jkl')                  # add multiple elements at once
&gt;&gt;&gt; d
deque(['g', 'h', 'i', 'j', 'k', 'l'])
&gt;&gt;&gt; d.rotate(1)                      # right rotation
&gt;&gt;&gt; d
deque(['l', 'g', 'h', 'i', 'j', 'k'])
&gt;&gt;&gt; d.rotate(-1)                     # left rotation
&gt;&gt;&gt; d
deque(['g', 'h', 'i', 'j', 'k', 'l'])

&gt;&gt;&gt; deque(reversed(d))               # make a new deque in reverse order
deque(['l', 'k', 'j', 'i', 'h', 'g'])
&gt;&gt;&gt; d.clear()                        # empty the deque
&gt;&gt;&gt; d.pop()                          # cannot pop from an empty deque
Traceback (most recent call last):
    File "&lt;pyshell#6&gt;", line 1, in -toplevel-
        d.pop()
IndexError: pop from an empty deque

&gt;&gt;&gt; d.extendleft('abc')              # extendleft() reverses the input order
&gt;&gt;&gt; d
deque(['c', 'b', 'a'])
</pre> <section id="deque-recipes"> <h3>
<a class="reference internal" href="#collections.deque" title="collections.deque"><code>deque</code></a> Recipes</h3> <p>This section shows various approaches to working with deques.</p> <p>Bounded length deques provide functionality similar to the <code>tail</code> filter in Unix:</p> <pre data-language="python">def tail(filename, n=10):
    'Return the last n lines of a file'
    with open(filename) as f:
        return deque(f, n)
</pre> <p>Another approach to using deques is to maintain a sequence of recently added elements by appending to the right and popping to the left:</p> <pre data-language="python">def moving_average(iterable, n=3):
    # moving_average([40, 30, 50, 46, 39, 44]) --&gt; 40.0 42.0 45.0 43.0
    # https://en.wikipedia.org/wiki/Moving_average
    it = iter(iterable)
    d = deque(itertools.islice(it, n-1))
    d.appendleft(0)
    s = sum(d)
    for elem in it:
        s += elem - d.popleft()
        d.append(elem)
        yield s / n
</pre> <p>A <a class="reference external" href="https://en.wikipedia.org/wiki/Round-robin_scheduling">round-robin scheduler</a> can be implemented with input iterators stored in a <a class="reference internal" href="#collections.deque" title="collections.deque"><code>deque</code></a>. Values are yielded from the active iterator in position zero. If that iterator is exhausted, it can be removed with <a class="reference internal" href="#collections.deque.popleft" title="collections.deque.popleft"><code>popleft()</code></a>; otherwise, it can be cycled back to the end with the <a class="reference internal" href="#collections.deque.rotate" title="collections.deque.rotate"><code>rotate()</code></a> method:</p> <pre data-language="python">def roundrobin(*iterables):
    "roundrobin('ABC', 'D', 'EF') --&gt; A D E B F C"
    iterators = deque(map(iter, iterables))
    while iterators:
        try:
            while True:
                yield next(iterators[0])
                iterators.rotate(-1)
        except StopIteration:
            # Remove an exhausted iterator.
            iterators.popleft()
</pre> <p>The <a class="reference internal" href="#collections.deque.rotate" title="collections.deque.rotate"><code>rotate()</code></a> method provides a way to implement <a class="reference internal" href="#collections.deque" title="collections.deque"><code>deque</code></a> slicing and deletion. For example, a pure Python implementation of <code>del d[n]</code> relies on the <code>rotate()</code> method to position elements to be popped:</p> <pre data-language="python">def delete_nth(d, n):
    d.rotate(-n)
    d.popleft()
    d.rotate(n)
</pre> <p>To implement <a class="reference internal" href="#collections.deque" title="collections.deque"><code>deque</code></a> slicing, use a similar approach applying <a class="reference internal" href="#collections.deque.rotate" title="collections.deque.rotate"><code>rotate()</code></a> to bring a target element to the left side of the deque. Remove old entries with <a class="reference internal" href="#collections.deque.popleft" title="collections.deque.popleft"><code>popleft()</code></a>, add new entries with <a class="reference internal" href="#collections.deque.extend" title="collections.deque.extend"><code>extend()</code></a>, and then reverse the rotation. With minor variations on that approach, it is easy to implement Forth style stack manipulations such as <code>dup</code>, <code>drop</code>, <code>swap</code>, <code>over</code>, <code>pick</code>, <code>rot</code>, and <code>roll</code>.</p> </section> </section> <section id="defaultdict-objects"> <h2>defaultdict objects</h2> <dl class="py class"> <dt class="sig sig-object py" id="collections.defaultdict">
<code>class collections.defaultdict(default_factory=None, /[, ...])</code> </dt> <dd>
<p>Return a new dictionary-like object. <a class="reference internal" href="#collections.defaultdict" title="collections.defaultdict"><code>defaultdict</code></a> is a subclass of the built-in <a class="reference internal" href="stdtypes#dict" title="dict"><code>dict</code></a> class. It overrides one method and adds one writable instance variable. The remaining functionality is the same as for the <a class="reference internal" href="stdtypes#dict" title="dict"><code>dict</code></a> class and is not documented here.</p> <p>The first argument provides the initial value for the <a class="reference internal" href="#collections.defaultdict.default_factory" title="collections.defaultdict.default_factory"><code>default_factory</code></a> attribute; it defaults to <code>None</code>. All remaining arguments are treated the same as if they were passed to the <a class="reference internal" href="stdtypes#dict" title="dict"><code>dict</code></a> constructor, including keyword arguments.</p> <p><a class="reference internal" href="#collections.defaultdict" title="collections.defaultdict"><code>defaultdict</code></a> objects support the following method in addition to the standard <a class="reference internal" href="stdtypes#dict" title="dict"><code>dict</code></a> operations:</p> <dl class="py method"> <dt class="sig sig-object py" id="collections.defaultdict.__missing__">
<code>__missing__(key)</code> </dt> <dd>
<p>If the <a class="reference internal" href="#collections.defaultdict.default_factory" title="collections.defaultdict.default_factory"><code>default_factory</code></a> attribute is <code>None</code>, this raises a <a class="reference internal" href="exceptions#KeyError" title="KeyError"><code>KeyError</code></a> exception with the <em>key</em> as argument.</p> <p>If <a class="reference internal" href="#collections.defaultdict.default_factory" title="collections.defaultdict.default_factory"><code>default_factory</code></a> is not <code>None</code>, it is called without arguments to provide a default value for the given <em>key</em>, this value is inserted in the dictionary for the <em>key</em>, and returned.</p> <p>If calling <a class="reference internal" href="#collections.defaultdict.default_factory" title="collections.defaultdict.default_factory"><code>default_factory</code></a> raises an exception this exception is propagated unchanged.</p> <p>This method is called by the <a class="reference internal" href="../reference/datamodel#object.__getitem__" title="object.__getitem__"><code>__getitem__()</code></a> method of the <a class="reference internal" href="stdtypes#dict" title="dict"><code>dict</code></a> class when the requested key is not found; whatever it returns or raises is then returned or raised by <a class="reference internal" href="../reference/datamodel#object.__getitem__" title="object.__getitem__"><code>__getitem__()</code></a>.</p> <p>Note that <a class="reference internal" href="#collections.defaultdict.__missing__" title="collections.defaultdict.__missing__"><code>__missing__()</code></a> is <em>not</em> called for any operations besides <a class="reference internal" href="../reference/datamodel#object.__getitem__" title="object.__getitem__"><code>__getitem__()</code></a>. This means that <code>get()</code> will, like normal dictionaries, return <code>None</code> as a default rather than using <a class="reference internal" href="#collections.defaultdict.default_factory" title="collections.defaultdict.default_factory"><code>default_factory</code></a>.</p> </dd>
</dl> <p><a class="reference internal" href="#collections.defaultdict" title="collections.defaultdict"><code>defaultdict</code></a> objects support the following instance variable:</p> <dl class="py attribute"> <dt class="sig sig-object py" id="collections.defaultdict.default_factory">
<code>default_factory</code> </dt> <dd>
<p>This attribute is used by the <a class="reference internal" href="#collections.defaultdict.__missing__" title="collections.defaultdict.__missing__"><code>__missing__()</code></a> method; it is initialized from the first argument to the constructor, if present, or to <code>None</code>, if absent.</p> </dd>
</dl> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.9: </span>Added merge (<code>|</code>) and update (<code>|=</code>) operators, specified in <span class="target" id="index-1"></span><a class="pep reference external" href="https://peps.python.org/pep-0584/"><strong>PEP 584</strong></a>.</p> </div> </dd>
</dl> <section id="defaultdict-examples"> <h3>
<a class="reference internal" href="#collections.defaultdict" title="collections.defaultdict"><code>defaultdict</code></a> Examples</h3> <p>Using <a class="reference internal" href="stdtypes#list" title="list"><code>list</code></a> as the <a class="reference internal" href="#collections.defaultdict.default_factory" title="collections.defaultdict.default_factory"><code>default_factory</code></a>, it is easy to group a sequence of key-value pairs into a dictionary of lists:</p> <pre data-language="python">&gt;&gt;&gt; s = [('yellow', 1), ('blue', 2), ('yellow', 3), ('blue', 4), ('red', 1)]
&gt;&gt;&gt; d = defaultdict(list)
&gt;&gt;&gt; for k, v in s:
...     d[k].append(v)
...
&gt;&gt;&gt; sorted(d.items())
[('blue', [2, 4]), ('red', [1]), ('yellow', [1, 3])]
</pre> <p>When each key is encountered for the first time, it is not already in the mapping; so an entry is automatically created using the <a class="reference internal" href="#collections.defaultdict.default_factory" title="collections.defaultdict.default_factory"><code>default_factory</code></a> function which returns an empty <a class="reference internal" href="stdtypes#list" title="list"><code>list</code></a>. The <code>list.append()</code> operation then attaches the value to the new list. When keys are encountered again, the look-up proceeds normally (returning the list for that key) and the <code>list.append()</code> operation adds another value to the list. This technique is simpler and faster than an equivalent technique using <a class="reference internal" href="stdtypes#dict.setdefault" title="dict.setdefault"><code>dict.setdefault()</code></a>:</p> <pre data-language="python">&gt;&gt;&gt; d = {}
&gt;&gt;&gt; for k, v in s:
...     d.setdefault(k, []).append(v)
...
&gt;&gt;&gt; sorted(d.items())
[('blue', [2, 4]), ('red', [1]), ('yellow', [1, 3])]
</pre> <p>Setting the <a class="reference internal" href="#collections.defaultdict.default_factory" title="collections.defaultdict.default_factory"><code>default_factory</code></a> to <a class="reference internal" href="functions#int" title="int"><code>int</code></a> makes the <a class="reference internal" href="#collections.defaultdict" title="collections.defaultdict"><code>defaultdict</code></a> useful for counting (like a bag or multiset in other languages):</p> <pre data-language="python">&gt;&gt;&gt; s = 'mississippi'
&gt;&gt;&gt; d = defaultdict(int)
&gt;&gt;&gt; for k in s:
...     d[k] += 1
...
&gt;&gt;&gt; sorted(d.items())
[('i', 4), ('m', 1), ('p', 2), ('s', 4)]
</pre> <p>When a letter is first encountered, it is missing from the mapping, so the <a class="reference internal" href="#collections.defaultdict.default_factory" title="collections.defaultdict.default_factory"><code>default_factory</code></a> function calls <a class="reference internal" href="functions#int" title="int"><code>int()</code></a> to supply a default count of zero. The increment operation then builds up the count for each letter.</p> <p>The function <a class="reference internal" href="functions#int" title="int"><code>int()</code></a> which always returns zero is just a special case of constant functions. A faster and more flexible way to create constant functions is to use a lambda function which can supply any constant value (not just zero):</p> <pre data-language="python">&gt;&gt;&gt; def constant_factory(value):
...     return lambda: value
...
&gt;&gt;&gt; d = defaultdict(constant_factory('&lt;missing&gt;'))
&gt;&gt;&gt; d.update(name='John', action='ran')
&gt;&gt;&gt; '%(name)s %(action)s to %(object)s' % d
'John ran to &lt;missing&gt;'
</pre> <p>Setting the <a class="reference internal" href="#collections.defaultdict.default_factory" title="collections.defaultdict.default_factory"><code>default_factory</code></a> to <a class="reference internal" href="stdtypes#set" title="set"><code>set</code></a> makes the <a class="reference internal" href="#collections.defaultdict" title="collections.defaultdict"><code>defaultdict</code></a> useful for building a dictionary of sets:</p> <pre data-language="python">&gt;&gt;&gt; s = [('red', 1), ('blue', 2), ('red', 3), ('blue', 4), ('red', 1), ('blue', 4)]
&gt;&gt;&gt; d = defaultdict(set)
&gt;&gt;&gt; for k, v in s:
...     d[k].add(v)
...
&gt;&gt;&gt; sorted(d.items())
[('blue', {2, 4}), ('red', {1, 3})]
</pre> </section> </section> <section id="namedtuple-factory-function-for-tuples-with-named-fields"> <h2>namedtuple() Factory Function for Tuples with Named Fields</h2> <p>Named tuples assign meaning to each position in a tuple and allow for more readable, self-documenting code. They can be used wherever regular tuples are used, and they add the ability to access fields by name instead of position index.</p> <dl class="py function"> <dt class="sig sig-object py" id="collections.namedtuple">
<code>collections.namedtuple(typename, field_names, *, rename=False, defaults=None, module=None)</code> </dt> <dd>
<p>Returns a new tuple subclass named <em>typename</em>. The new subclass is used to create tuple-like objects that have fields accessible by attribute lookup as well as being indexable and iterable. Instances of the subclass also have a helpful docstring (with typename and field_names) and a helpful <code>__repr__()</code> method which lists the tuple contents in a <code>name=value</code> format.</p> <p>The <em>field_names</em> are a sequence of strings such as <code>['x', 'y']</code>. Alternatively, <em>field_names</em> can be a single string with each fieldname separated by whitespace and/or commas, for example <code>'x y'</code> or <code>'x, y'</code>.</p> <p>Any valid Python identifier may be used for a fieldname except for names starting with an underscore. Valid identifiers consist of letters, digits, and underscores but do not start with a digit or underscore and cannot be a <a class="reference internal" href="keyword#module-keyword" title="keyword: Test whether a string is a keyword in Python."><code>keyword</code></a> such as <em>class</em>, <em>for</em>, <em>return</em>, <em>global</em>, <em>pass</em>, or <em>raise</em>.</p> <p>If <em>rename</em> is true, invalid fieldnames are automatically replaced with positional names. For example, <code>['abc', 'def', 'ghi', 'abc']</code> is converted to <code>['abc', '_1', 'ghi', '_3']</code>, eliminating the keyword <code>def</code> and the duplicate fieldname <code>abc</code>.</p> <p><em>defaults</em> can be <code>None</code> or an <a class="reference internal" href="../glossary#term-iterable"><span class="xref std std-term">iterable</span></a> of default values. Since fields with a default value must come after any fields without a default, the <em>defaults</em> are applied to the rightmost parameters. For example, if the fieldnames are <code>['x', 'y', 'z']</code> and the defaults are <code>(1, 2)</code>, then <code>x</code> will be a required argument, <code>y</code> will default to <code>1</code>, and <code>z</code> will default to <code>2</code>.</p> <p>If <em>module</em> is defined, the <code>__module__</code> attribute of the named tuple is set to that value.</p> <p>Named tuple instances do not have per-instance dictionaries, so they are lightweight and require no more memory than regular tuples.</p> <p>To support pickling, the named tuple class should be assigned to a variable that matches <em>typename</em>.</p> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.1: </span>Added support for <em>rename</em>.</p> </div> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.6: </span>The <em>verbose</em> and <em>rename</em> parameters became <a class="reference internal" href="../glossary#keyword-only-parameter"><span class="std std-ref">keyword-only arguments</span></a>.</p> </div> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.6: </span>Added the <em>module</em> parameter.</p> </div> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.7: </span>Removed the <em>verbose</em> parameter and the <code>_source</code> attribute.</p> </div> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.7: </span>Added the <em>defaults</em> parameter and the <code>_field_defaults</code> attribute.</p> </div> </dd>
</dl> <pre data-language="pycon3">&gt;&gt;&gt; # Basic example
&gt;&gt;&gt; Point = namedtuple('Point', ['x', 'y'])
&gt;&gt;&gt; p = Point(11, y=22)     # instantiate with positional or keyword arguments
&gt;&gt;&gt; p[0] + p[1]             # indexable like the plain tuple (11, 22)
33
&gt;&gt;&gt; x, y = p                # unpack like a regular tuple
&gt;&gt;&gt; x, y
(11, 22)
&gt;&gt;&gt; p.x + p.y               # fields also accessible by name
33
&gt;&gt;&gt; p                       # readable __repr__ with a name=value style
Point(x=11, y=22)
</pre> <p>Named tuples are especially useful for assigning field names to result tuples returned by the <a class="reference internal" href="csv#module-csv" title="csv: Write and read tabular data to and from delimited files."><code>csv</code></a> or <a class="reference internal" href="sqlite3#module-sqlite3" title="sqlite3: A DB-API 2.0 implementation using SQLite 3.x."><code>sqlite3</code></a> modules:</p> <pre data-language="python">EmployeeRecord = namedtuple('EmployeeRecord', 'name, age, title, department, paygrade')

import csv
for emp in map(EmployeeRecord._make, csv.reader(open("employees.csv", "rb"))):
    print(emp.name, emp.title)

import sqlite3
conn = sqlite3.connect('/companydata')
cursor = conn.cursor()
cursor.execute('SELECT name, age, title, department, paygrade FROM employees')
for emp in map(EmployeeRecord._make, cursor.fetchall()):
    print(emp.name, emp.title)
</pre> <p>In addition to the methods inherited from tuples, named tuples support three additional methods and two attributes. To prevent conflicts with field names, the method and attribute names start with an underscore.</p> <dl class="py method"> <dt class="sig sig-object py" id="collections.somenamedtuple._make">
<code>classmethod somenamedtuple._make(iterable)</code> </dt> <dd>
<p>Class method that makes a new instance from an existing sequence or iterable.</p> <pre data-language="pycon3">&gt;&gt;&gt; t = [11, 22]
&gt;&gt;&gt; Point._make(t)
Point(x=11, y=22)
</pre> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="collections.somenamedtuple._asdict">
<code>somenamedtuple._asdict()</code> </dt> <dd>
<p>Return a new <a class="reference internal" href="stdtypes#dict" title="dict"><code>dict</code></a> which maps field names to their corresponding values:</p> <pre data-language="pycon3">&gt;&gt;&gt; p = Point(x=11, y=22)
&gt;&gt;&gt; p._asdict()
{'x': 11, 'y': 22}
</pre> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.1: </span>Returns an <a class="reference internal" href="#collections.OrderedDict" title="collections.OrderedDict"><code>OrderedDict</code></a> instead of a regular <a class="reference internal" href="stdtypes#dict" title="dict"><code>dict</code></a>.</p> </div> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.8: </span>Returns a regular <a class="reference internal" href="stdtypes#dict" title="dict"><code>dict</code></a> instead of an <a class="reference internal" href="#collections.OrderedDict" title="collections.OrderedDict"><code>OrderedDict</code></a>. As of Python 3.7, regular dicts are guaranteed to be ordered. If the extra features of <a class="reference internal" href="#collections.OrderedDict" title="collections.OrderedDict"><code>OrderedDict</code></a> are required, the suggested remediation is to cast the result to the desired type: <code>OrderedDict(nt._asdict())</code>.</p> </div> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="collections.somenamedtuple._replace">
<code>somenamedtuple._replace(**kwargs)</code> </dt> <dd>
<p>Return a new instance of the named tuple replacing specified fields with new values:</p> <pre data-language="python">&gt;&gt;&gt; p = Point(x=11, y=22)
&gt;&gt;&gt; p._replace(x=33)
Point(x=33, y=22)

&gt;&gt;&gt; for partnum, record in inventory.items():
...     inventory[partnum] = record._replace(price=newprices[partnum], timestamp=time.now())
</pre> </dd>
</dl> <dl class="py attribute"> <dt class="sig sig-object py" id="collections.somenamedtuple._fields">
<code>somenamedtuple._fields</code> </dt> <dd>
<p>Tuple of strings listing the field names. Useful for introspection and for creating new named tuple types from existing named tuples.</p> <pre data-language="pycon3">&gt;&gt;&gt; p._fields            # view the field names
('x', 'y')

&gt;&gt;&gt; Color = namedtuple('Color', 'red green blue')
&gt;&gt;&gt; Pixel = namedtuple('Pixel', Point._fields + Color._fields)
&gt;&gt;&gt; Pixel(11, 22, 128, 255, 0)
Pixel(x=11, y=22, red=128, green=255, blue=0)
</pre> </dd>
</dl> <dl class="py attribute"> <dt class="sig sig-object py" id="collections.somenamedtuple._field_defaults">
<code>somenamedtuple._field_defaults</code> </dt> <dd>
<p>Dictionary mapping field names to default values.</p> <pre data-language="pycon3">&gt;&gt;&gt; Account = namedtuple('Account', ['type', 'balance'], defaults=[0])
&gt;&gt;&gt; Account._field_defaults
{'balance': 0}
&gt;&gt;&gt; Account('premium')
Account(type='premium', balance=0)
</pre> </dd>
</dl> <p>To retrieve a field whose name is stored in a string, use the <a class="reference internal" href="functions#getattr" title="getattr"><code>getattr()</code></a> function:</p> <pre data-language="python">&gt;&gt;&gt; getattr(p, 'x')
11
</pre> <p>To convert a dictionary to a named tuple, use the double-star-operator (as described in <a class="reference internal" href="../tutorial/controlflow#tut-unpacking-arguments"><span class="std std-ref">Unpacking Argument Lists</span></a>):</p> <pre data-language="python">&gt;&gt;&gt; d = {'x': 11, 'y': 22}
&gt;&gt;&gt; Point(**d)
Point(x=11, y=22)
</pre> <p>Since a named tuple is a regular Python class, it is easy to add or change functionality with a subclass. Here is how to add a calculated field and a fixed-width print format:</p> <pre data-language="pycon3">&gt;&gt;&gt; class Point(namedtuple('Point', ['x', 'y'])):
...     __slots__ = ()
...     @property
...     def hypot(self):
...         return (self.x ** 2 + self.y ** 2) ** 0.5
...     def __str__(self):
...         return 'Point: x=%6.3f  y=%6.3f  hypot=%6.3f' % (self.x, self.y, self.hypot)

&gt;&gt;&gt; for p in Point(3, 4), Point(14, 5/7):
...     print(p)
Point: x= 3.000  y= 4.000  hypot= 5.000
Point: x=14.000  y= 0.714  hypot=14.018
</pre> <p>The subclass shown above sets <code>__slots__</code> to an empty tuple. This helps keep memory requirements low by preventing the creation of instance dictionaries.</p> <p>Subclassing is not useful for adding new, stored fields. Instead, simply create a new named tuple type from the <a class="reference internal" href="#collections.somenamedtuple._fields" title="collections.somenamedtuple._fields"><code>_fields</code></a> attribute:</p> <pre data-language="python">&gt;&gt;&gt; Point3D = namedtuple('Point3D', Point._fields + ('z',))
</pre> <p>Docstrings can be customized by making direct assignments to the <code>__doc__</code> fields:</p> <pre data-language="python">&gt;&gt;&gt; Book = namedtuple('Book', ['id', 'title', 'authors'])
&gt;&gt;&gt; Book.__doc__ += ': Hardcover book in active collection'
&gt;&gt;&gt; Book.id.__doc__ = '13-digit ISBN'
&gt;&gt;&gt; Book.title.__doc__ = 'Title of first printing'
&gt;&gt;&gt; Book.authors.__doc__ = 'List of authors sorted by last name'
</pre> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.5: </span>Property docstrings became writeable.</p> </div> <div class="admonition seealso"> <p class="admonition-title">See also</p> <ul> <li>
<p>See <a class="reference internal" href="typing#typing.NamedTuple" title="typing.NamedTuple"><code>typing.NamedTuple</code></a> for a way to add type hints for named tuples. It also provides an elegant notation using the <a class="reference internal" href="../reference/compound_stmts#class"><code>class</code></a> keyword:</p> <pre data-language="python">class Component(NamedTuple):
    part_number: int
    weight: float
    description: Optional[str] = None
</pre> </li> <li>See <a class="reference internal" href="types#types.SimpleNamespace" title="types.SimpleNamespace"><code>types.SimpleNamespace()</code></a> for a mutable namespace based on an underlying dictionary instead of a tuple.</li> <li>The <a class="reference internal" href="dataclasses#module-dataclasses" title="dataclasses: Generate special methods on user-defined classes."><code>dataclasses</code></a> module provides a decorator and functions for automatically adding generated special methods to user-defined classes.</li> </ul> </div> </section> <section id="ordereddict-objects"> <h2>OrderedDict objects</h2> <p>Ordered dictionaries are just like regular dictionaries but have some extra capabilities relating to ordering operations. They have become less important now that the built-in <a class="reference internal" href="stdtypes#dict" title="dict"><code>dict</code></a> class gained the ability to remember insertion order (this new behavior became guaranteed in Python 3.7).</p> <p>Some differences from <a class="reference internal" href="stdtypes#dict" title="dict"><code>dict</code></a> still remain:</p> <ul> <li>The regular <a class="reference internal" href="stdtypes#dict" title="dict"><code>dict</code></a> was designed to be very good at mapping operations. Tracking insertion order was secondary.</li> <li>The <a class="reference internal" href="#collections.OrderedDict" title="collections.OrderedDict"><code>OrderedDict</code></a> was designed to be good at reordering operations. Space efficiency, iteration speed, and the performance of update operations were secondary.</li> <li>The <a class="reference internal" href="#collections.OrderedDict" title="collections.OrderedDict"><code>OrderedDict</code></a> algorithm can handle frequent reordering operations better than <a class="reference internal" href="stdtypes#dict" title="dict"><code>dict</code></a>. As shown in the recipes below, this makes it suitable for implementing various kinds of LRU caches.</li> <li>
<p>The equality operation for <a class="reference internal" href="#collections.OrderedDict" title="collections.OrderedDict"><code>OrderedDict</code></a> checks for matching order.</p> <p>A regular <a class="reference internal" href="stdtypes#dict" title="dict"><code>dict</code></a> can emulate the order sensitive equality test with <code>p == q and all(k1 == k2 for k1, k2 in zip(p, q))</code>.</p> </li> <li>
<p>The <code>popitem()</code> method of <a class="reference internal" href="#collections.OrderedDict" title="collections.OrderedDict"><code>OrderedDict</code></a> has a different signature. It accepts an optional argument to specify which item is popped.</p> <p>A regular <a class="reference internal" href="stdtypes#dict" title="dict"><code>dict</code></a> can emulate OrderedDict’s <code>od.popitem(last=True)</code> with <code>d.popitem()</code> which is guaranteed to pop the rightmost (last) item.</p> <p>A regular <a class="reference internal" href="stdtypes#dict" title="dict"><code>dict</code></a> can emulate OrderedDict’s <code>od.popitem(last=False)</code> with <code>(k := next(iter(d)), d.pop(k))</code> which will return and remove the leftmost (first) item if it exists.</p> </li> <li>
<p><a class="reference internal" href="#collections.OrderedDict" title="collections.OrderedDict"><code>OrderedDict</code></a> has a <code>move_to_end()</code> method to efficiently reposition an element to an endpoint.</p> <p>A regular <a class="reference internal" href="stdtypes#dict" title="dict"><code>dict</code></a> can emulate OrderedDict’s <code>od.move_to_end(k,
last=True)</code> with <code>d[k] = d.pop(k)</code> which will move the key and its associated value to the rightmost (last) position.</p> <p>A regular <a class="reference internal" href="stdtypes#dict" title="dict"><code>dict</code></a> does not have an efficient equivalent for OrderedDict’s <code>od.move_to_end(k, last=False)</code> which moves the key and its associated value to the leftmost (first) position.</p> </li> <li>Until Python 3.8, <a class="reference internal" href="stdtypes#dict" title="dict"><code>dict</code></a> lacked a <code>__reversed__()</code> method.</li> </ul> <dl class="py class"> <dt class="sig sig-object py" id="collections.OrderedDict">
<code>class collections.OrderedDict([items])</code> </dt> <dd>
<p>Return an instance of a <a class="reference internal" href="stdtypes#dict" title="dict"><code>dict</code></a> subclass that has methods specialized for rearranging dictionary order.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.1.</span></p> </div> <dl class="py method"> <dt class="sig sig-object py" id="collections.OrderedDict.popitem">
<code>popitem(last=True)</code> </dt> <dd>
<p>The <a class="reference internal" href="#collections.OrderedDict.popitem" title="collections.OrderedDict.popitem"><code>popitem()</code></a> method for ordered dictionaries returns and removes a (key, value) pair. The pairs are returned in <abbr title="last-in, first-out">LIFO</abbr> order if <em>last</em> is true or <abbr title="first-in, first-out">FIFO</abbr> order if false.</p> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="collections.OrderedDict.move_to_end">
<code>move_to_end(key, last=True)</code> </dt> <dd>
<p>Move an existing <em>key</em> to either end of an ordered dictionary. The item is moved to the right end if <em>last</em> is true (the default) or to the beginning if <em>last</em> is false. Raises <a class="reference internal" href="exceptions#KeyError" title="KeyError"><code>KeyError</code></a> if the <em>key</em> does not exist:</p> <pre data-language="pycon3">&gt;&gt;&gt; d = OrderedDict.fromkeys('abcde')
&gt;&gt;&gt; d.move_to_end('b')
&gt;&gt;&gt; ''.join(d)
'acdeb'
&gt;&gt;&gt; d.move_to_end('b', last=False)
&gt;&gt;&gt; ''.join(d)
'bacde'
</pre> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.2.</span></p> </div> </dd>
</dl> </dd>
</dl> <p>In addition to the usual mapping methods, ordered dictionaries also support reverse iteration using <a class="reference internal" href="functions#reversed" title="reversed"><code>reversed()</code></a>.</p> <p>Equality tests between <a class="reference internal" href="#collections.OrderedDict" title="collections.OrderedDict"><code>OrderedDict</code></a> objects are order-sensitive and are implemented as <code>list(od1.items())==list(od2.items())</code>. Equality tests between <a class="reference internal" href="#collections.OrderedDict" title="collections.OrderedDict"><code>OrderedDict</code></a> objects and other <a class="reference internal" href="collections.abc#collections.abc.Mapping" title="collections.abc.Mapping"><code>Mapping</code></a> objects are order-insensitive like regular dictionaries. This allows <a class="reference internal" href="#collections.OrderedDict" title="collections.OrderedDict"><code>OrderedDict</code></a> objects to be substituted anywhere a regular dictionary is used.</p> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.5: </span>The items, keys, and values <a class="reference internal" href="../glossary#term-dictionary-view"><span class="xref std std-term">views</span></a> of <a class="reference internal" href="#collections.OrderedDict" title="collections.OrderedDict"><code>OrderedDict</code></a> now support reverse iteration using <a class="reference internal" href="functions#reversed" title="reversed"><code>reversed()</code></a>.</p> </div> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.6: </span>With the acceptance of <span class="target" id="index-2"></span><a class="pep reference external" href="https://peps.python.org/pep-0468/"><strong>PEP 468</strong></a>, order is retained for keyword arguments passed to the <a class="reference internal" href="#collections.OrderedDict" title="collections.OrderedDict"><code>OrderedDict</code></a> constructor and its <code>update()</code> method.</p> </div> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.9: </span>Added merge (<code>|</code>) and update (<code>|=</code>) operators, specified in <span class="target" id="index-3"></span><a class="pep reference external" href="https://peps.python.org/pep-0584/"><strong>PEP 584</strong></a>.</p> </div> <section id="ordereddict-examples-and-recipes"> <h3>
<a class="reference internal" href="#collections.OrderedDict" title="collections.OrderedDict"><code>OrderedDict</code></a> Examples and Recipes</h3> <p>It is straightforward to create an ordered dictionary variant that remembers the order the keys were <em>last</em> inserted. If a new entry overwrites an existing entry, the original insertion position is changed and moved to the end:</p> <pre data-language="python">class LastUpdatedOrderedDict(OrderedDict):
    'Store items in the order the keys were last added'

    def __setitem__(self, key, value):
        super().__setitem__(key, value)
        self.move_to_end(key)
</pre> <p>An <a class="reference internal" href="#collections.OrderedDict" title="collections.OrderedDict"><code>OrderedDict</code></a> would also be useful for implementing variants of <a class="reference internal" href="functools#functools.lru_cache" title="functools.lru_cache"><code>functools.lru_cache()</code></a>:</p> <pre data-language="python">from collections import OrderedDict
from time import time

class TimeBoundedLRU:
    "LRU Cache that invalidates and refreshes old entries."

    def __init__(self, func, maxsize=128, maxage=30):
        self.cache = OrderedDict()      # { args : (timestamp, result)}
        self.func = func
        self.maxsize = maxsize
        self.maxage = maxage

    def __call__(self, *args):
        if args in self.cache:
            self.cache.move_to_end(args)
            timestamp, result = self.cache[args]
            if time() - timestamp &lt;= self.maxage:
                return result
        result = self.func(*args)
        self.cache[args] = time(), result
        if len(self.cache) &gt; self.maxsize:
            self.cache.popitem(0)
        return result
</pre> <pre data-language="python">class MultiHitLRUCache:
    """ LRU cache that defers caching a result until
        it has been requested multiple times.

        To avoid flushing the LRU cache with one-time requests,
        we don't cache until a request has been made more than once.

    """

    def __init__(self, func, maxsize=128, maxrequests=4096, cache_after=1):
        self.requests = OrderedDict()   # { uncached_key : request_count }
        self.cache = OrderedDict()      # { cached_key : function_result }
        self.func = func
        self.maxrequests = maxrequests  # max number of uncached requests
        self.maxsize = maxsize          # max number of stored return values
        self.cache_after = cache_after

    def __call__(self, *args):
        if args in self.cache:
            self.cache.move_to_end(args)
            return self.cache[args]
        result = self.func(*args)
        self.requests[args] = self.requests.get(args, 0) + 1
        if self.requests[args] &lt;= self.cache_after:
            self.requests.move_to_end(args)
            if len(self.requests) &gt; self.maxrequests:
                self.requests.popitem(0)
        else:
            self.requests.pop(args, None)
            self.cache[args] = result
            if len(self.cache) &gt; self.maxsize:
                self.cache.popitem(0)
        return result
</pre> </section> </section> <section id="userdict-objects"> <h2>UserDict objects</h2> <p>The class, <a class="reference internal" href="#collections.UserDict" title="collections.UserDict"><code>UserDict</code></a> acts as a wrapper around dictionary objects. The need for this class has been partially supplanted by the ability to subclass directly from <a class="reference internal" href="stdtypes#dict" title="dict"><code>dict</code></a>; however, this class can be easier to work with because the underlying dictionary is accessible as an attribute.</p> <dl class="py class"> <dt class="sig sig-object py" id="collections.UserDict">
<code>class collections.UserDict([initialdata])</code> </dt> <dd>
<p>Class that simulates a dictionary. The instance’s contents are kept in a regular dictionary, which is accessible via the <a class="reference internal" href="#collections.UserDict.data" title="collections.UserDict.data"><code>data</code></a> attribute of <a class="reference internal" href="#collections.UserDict" title="collections.UserDict"><code>UserDict</code></a> instances. If <em>initialdata</em> is provided, <a class="reference internal" href="#collections.UserDict.data" title="collections.UserDict.data"><code>data</code></a> is initialized with its contents; note that a reference to <em>initialdata</em> will not be kept, allowing it to be used for other purposes.</p> <p>In addition to supporting the methods and operations of mappings, <a class="reference internal" href="#collections.UserDict" title="collections.UserDict"><code>UserDict</code></a> instances provide the following attribute:</p> <dl class="py attribute"> <dt class="sig sig-object py" id="collections.UserDict.data">
<code>data</code> </dt> <dd>
<p>A real dictionary used to store the contents of the <a class="reference internal" href="#collections.UserDict" title="collections.UserDict"><code>UserDict</code></a> class.</p> </dd>
</dl> </dd>
</dl> </section> <section id="userlist-objects"> <h2>UserList objects</h2> <p>This class acts as a wrapper around list objects. It is a useful base class for your own list-like classes which can inherit from them and override existing methods or add new ones. In this way, one can add new behaviors to lists.</p> <p>The need for this class has been partially supplanted by the ability to subclass directly from <a class="reference internal" href="stdtypes#list" title="list"><code>list</code></a>; however, this class can be easier to work with because the underlying list is accessible as an attribute.</p> <dl class="py class"> <dt class="sig sig-object py" id="collections.UserList">
<code>class collections.UserList([list])</code> </dt> <dd>
<p>Class that simulates a list. The instance’s contents are kept in a regular list, which is accessible via the <a class="reference internal" href="#collections.UserList.data" title="collections.UserList.data"><code>data</code></a> attribute of <a class="reference internal" href="#collections.UserList" title="collections.UserList"><code>UserList</code></a> instances. The instance’s contents are initially set to a copy of <em>list</em>, defaulting to the empty list <code>[]</code>. <em>list</em> can be any iterable, for example a real Python list or a <a class="reference internal" href="#collections.UserList" title="collections.UserList"><code>UserList</code></a> object.</p> <p>In addition to supporting the methods and operations of mutable sequences, <a class="reference internal" href="#collections.UserList" title="collections.UserList"><code>UserList</code></a> instances provide the following attribute:</p> <dl class="py attribute"> <dt class="sig sig-object py" id="collections.UserList.data">
<code>data</code> </dt> <dd>
<p>A real <a class="reference internal" href="stdtypes#list" title="list"><code>list</code></a> object used to store the contents of the <a class="reference internal" href="#collections.UserList" title="collections.UserList"><code>UserList</code></a> class.</p> </dd>
</dl> </dd>
</dl> <p><strong>Subclassing requirements:</strong> Subclasses of <a class="reference internal" href="#collections.UserList" title="collections.UserList"><code>UserList</code></a> are expected to offer a constructor which can be called with either no arguments or one argument. List operations which return a new sequence attempt to create an instance of the actual implementation class. To do so, it assumes that the constructor can be called with a single parameter, which is a sequence object used as a data source.</p> <p>If a derived class does not wish to comply with this requirement, all of the special methods supported by this class will need to be overridden; please consult the sources for information about the methods which need to be provided in that case.</p> </section> <section id="userstring-objects"> <h2>UserString objects</h2> <p>The class, <a class="reference internal" href="#collections.UserString" title="collections.UserString"><code>UserString</code></a> acts as a wrapper around string objects. The need for this class has been partially supplanted by the ability to subclass directly from <a class="reference internal" href="stdtypes#str" title="str"><code>str</code></a>; however, this class can be easier to work with because the underlying string is accessible as an attribute.</p> <dl class="py class"> <dt class="sig sig-object py" id="collections.UserString">
<code>class collections.UserString(seq)</code> </dt> <dd>
<p>Class that simulates a string object. The instance’s content is kept in a regular string object, which is accessible via the <a class="reference internal" href="#collections.UserString.data" title="collections.UserString.data"><code>data</code></a> attribute of <a class="reference internal" href="#collections.UserString" title="collections.UserString"><code>UserString</code></a> instances. The instance’s contents are initially set to a copy of <em>seq</em>. The <em>seq</em> argument can be any object which can be converted into a string using the built-in <a class="reference internal" href="stdtypes#str" title="str"><code>str()</code></a> function.</p> <p>In addition to supporting the methods and operations of strings, <a class="reference internal" href="#collections.UserString" title="collections.UserString"><code>UserString</code></a> instances provide the following attribute:</p> <dl class="py attribute"> <dt class="sig sig-object py" id="collections.UserString.data">
<code>data</code> </dt> <dd>
<p>A real <a class="reference internal" href="stdtypes#str" title="str"><code>str</code></a> object used to store the contents of the <a class="reference internal" href="#collections.UserString" title="collections.UserString"><code>UserString</code></a> class.</p> </dd>
</dl> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.5: </span>New methods <code>__getnewargs__</code>, <code>__rmod__</code>, <code>casefold</code>, <code>format_map</code>, <code>isprintable</code>, and <code>maketrans</code>.</p> </div> </dd>
</dl> </section> <div class="_attribution">
  <p class="_attribution-p">
    &copy; 2001&ndash;2023 Python Software Foundation<br>Licensed under the PSF License.<br>
    <a href="https://docs.python.org/3.12/library/collections.html" class="_attribution-link">https://docs.python.org/3.12/library/collections.html</a>
  </p>
</div>