Python Reference ยท Lists, Tuples and Ranges
Python tuple methods and namedtuple
Reference for Python tuple methods count() and index(), plus collections.namedtuple: named fields, _asdict(), _replace(), _fields and typing.NamedTuple.
A tuple is immutable, so it has only two methods of its own: count() and index(). Both only read the tuple. Everything else you do with tuples, such as slicing, concatenating, comparing and unpacking, uses operators and built-in functions.
When positions in a tuple carry meaning, collections.namedtuple (or the class-based typing.NamedTuple) gives each position a name. A named tuple is still a real tuple: it is immutable, unpackable and indexable, and it uses no more memory than a plain tuple.
point = (3, 4, 3) print(point.count(3), point.index(4)) # 2 1
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.
Syntax
tuple.count(value) tuple.index(value[, start[, end]])
| Name | Description |
|---|---|
value |
The item to look for, compared with == (identity is checked first). |
start, end |
Optional, for index(). Search only the slice from start up to, but not including, end. |
Return value: count() returns the number of matching items (an int, possibly 0). index() returns the position of the first match, counted from the start of the whole tuple, not from start.
Raises: index() raises ValueError when the value is not found. count() never raises for a missing value.
Named tuples
collections.namedtuple(typename, field_names, *, rename=False, defaults=None)
namedtuple() builds a new tuple subclass. field_names may be a list of strings or a single string such as "x y". Instances support attribute access (p.x), indexing, unpacking and everything else a tuple does.
| Member | Description |
|---|---|
_fields |
A tuple of the field names. |
_asdict() |
Returns a regular dict mapping names to values. |
_replace(**kwargs) |
Returns a new instance with some fields changed. |
_make(iterable) |
Class method that builds an instance from an iterable. |
Usage notes
- Methods never change the tuple. There is no
append(),remove()orsort(). Usesorted(t)to get a sorted list. - Order matters for
index(). It returns the first match only. To find every position, use[i for i, v in enumerate(t) if v == target]. - Mutable contents. A tuple holding a list is immutable only in its slots; the list inside can still change, and then the tuple cannot be hashed.
- Named tuples are immutable. Assigning to a field raises
AttributeError; use_replace()to get a changed copy. - Field names must be valid identifiers, cannot start with an underscore and cannot be keywords.
rename=Truereplaces bad names with positional ones. defaultsapply to the rightmost fields:namedtuple("P", "a b", defaults=[0])givesba default.- Equality ignores the type.
Point(1, 2) == (1, 2)isTrue, which can surprise you. - When to prefer a dataclass: if you need mutation, methods with state or inheritance, see
dataclasses.
Related
tuple,list.count(),list.index(), unpacking- Lessons: Tuples, Collections, Dataclasses