|
1 | 1 | --- |
2 | 2 | Title: 'namedtuple' |
3 | | -Description: 'A tuple subclass with named fields' |
| 3 | +Description: 'Creates tuple subclasses with named fields for improved code readability in Python namedtuple structures.' |
4 | 4 | Subjects: |
5 | 5 | - 'Computer Science' |
6 | 6 | - 'Data Science' |
7 | 7 | Tags: |
| 8 | + - 'Collections' |
| 9 | + - 'Data Structures' |
8 | 10 | - 'Tuples' |
9 | | - - 'Data Types' |
10 | 11 | CatalogContent: |
11 | 12 | - 'learn-python-3' |
12 | 13 | - 'paths/computer-science' |
13 | 14 | --- |
14 | 15 |
|
15 | | -A **namedtuple** is a data type in the `collections` module. It is a [`tuple`](https://www.codecademy.com/resources/docs/python/tuples) subclass that allows you to create immutable objects with named fields. This improves code readability by providing meaningful names for each element and making the code more explicit. |
| 16 | +A **`namedtuple`** is a factory function in Python's `collections` module that creates [`tuple`](https://www.codecademy.com/resources/docs/python/tuples) subclasses with named fields. It provides an immutable data structure that allows access to elements through descriptive field names instead of numeric indices, making Python `namedtuple` structures more readable and self-documenting while maintaining the memory efficiency and performance characteristics of regular tuples. |
16 | 17 |
|
17 | 18 | ## Syntax |
18 | 19 |
|
19 | 20 | ```pseudo |
20 | | -namedtuple(typename, field_names) |
| 21 | +namedtuple(typename, field_names, *, rename=False, defaults=None, module=None) |
21 | 22 | ``` |
22 | 23 |
|
23 | | -- `typename`: The name of the new tuple subclass. |
24 | | -- `field_names`: It represents the names of the fields in the named tuple. |
| 24 | +**Parameters:** |
25 | 25 |
|
26 | | -## Additional Methods |
| 26 | +- `typename`: A string specifying the name of the new tuple subclass |
| 27 | +- `field_names`: A sequence of strings or a single string with field names separated by whitespace and/or commas |
| 28 | +- `rename`: If `True`, invalid field names are automatically replaced with positional names |
| 29 | +- `defaults`: An iterable of default values for the rightmost parameters |
| 30 | +- `module`: Value for the `__module__` field |
27 | 31 |
|
28 | | -There are 3 specific `namedtuple` methods in addition to the standard methods inherited from tuples. All methods begin with an underscore to avoid conflicts with field names. |
| 32 | +**Return value:** |
29 | 33 |
|
30 | | --`._make(iterable)`: (Class method) Creates a new instance based on an existing sequence or iterable. |
| 34 | +A new tuple subclass with named fields that can be accessed via dot notation. |
31 | 35 |
|
32 | | --`._asdict()`: Returns a [`dict`](https://www.codecademy.com/resources/docs/python/dictionaries) with matching field names and values. |
| 36 | +## Example 1: Python `namedtuple` Basic Example |
33 | 37 |
|
34 | | --`._replace(kwarg)`: Returns a new instance with fields replaced by the value provided as a keyword argument. |
| 38 | +This example demonstrates how to create a Python `namedtuple`, access its elements, and perform basic operations in Python: |
35 | 39 |
|
36 | | -There are 2 specific attributes `._fields` and `_field_defaults` that will allow you respectively to list field names and to return a [`dict`](https://www.codecademy.com/resources/docs/python/dictionaries) with field names related to their default values. |
| 40 | +```py |
| 41 | +from collections import namedtuple |
| 42 | + |
| 43 | +# Create a namedtuple |
| 44 | +Person = namedtuple('Person', ['name', 'age', 'city']) |
| 45 | + |
| 46 | +# Create instances |
| 47 | +john = Person('John Doe', 30, 'New York') |
| 48 | +jane = Person(name='Jane Smith', age=25, city='Boston') |
| 49 | + |
| 50 | +print(john) |
| 51 | +print(jane) |
| 52 | + |
| 53 | +# Access Operations |
| 54 | +print("Access by field name:", john.name) |
| 55 | +print("Access by index:", john[0]) |
| 56 | +print("Access using getattr:", getattr(john, 'age')) |
| 57 | + |
| 58 | +# Conversion Operations |
| 59 | +print("Convert to dict:", john._asdict()) |
| 60 | + |
| 61 | +# Additional Operations |
| 62 | +print("Field names:", Person._fields) |
| 63 | +new_person = john._replace(age=31) |
| 64 | +print("After replace:", new_person) |
| 65 | +``` |
| 66 | + |
| 67 | +This example results in the following output: |
| 68 | + |
| 69 | +```shell |
| 70 | +Person(name='John Doe', age=30, city='New York') |
| 71 | +Person(name='Jane Smith', age=25, city='Boston') |
| 72 | +Access by field name: John Doe |
| 73 | +Access by index: John Doe |
| 74 | +Access using getattr: 30 |
| 75 | +Convert to dict: OrderedDict([('name', 'John Doe'), ('age', 30), ('city', 'New York')]) |
| 76 | +Field names: ('name', 'age', 'city') |
| 77 | +After replace: Person(name='John Doe', age=31, city='New York') |
| 78 | +``` |
| 79 | + |
| 80 | +## Conversion Operations |
| 81 | + |
| 82 | +`namedtuple` provides several useful methods to convert between different data types and create new instances from existing data. These conversion operations make it easy to work with `namedtuples` alongside other Python data structures like lists, dictionaries, and iterables. There are three main conversion operations available: |
| 83 | + |
| 84 | +- Using `_make()`: Creates `namedtuple` instances from iterables |
| 85 | +- Using `_asdict()`: Converts namedtuples to ordered dictionaries |
| 86 | +- Using `**` operator: Creates namedtuples from dictionaries using unpacking |
| 87 | + |
| 88 | +Let's examine each conversion operation. |
| 89 | + |
| 90 | +### Example 2: Using Named Tuples Python `_make()` Method |
| 91 | + |
| 92 | +Creates a `namedtuple` instance from an existing iterable, making it easy to convert lists, tuples, or other sequences into namedtuples: |
| 93 | + |
| 94 | +```py |
| 95 | +from collections import namedtuple |
| 96 | + |
| 97 | +# Create namedtuple class |
| 98 | +Coordinate = namedtuple('Coordinate', ['x', 'y', 'z']) |
37 | 99 |
|
38 | | -## Example |
| 100 | +# Create from different iterables |
| 101 | +point_list = [10, 20, 30] |
| 102 | +point_tuple = (5, 15, 25) |
39 | 103 |
|
40 | | -In the following example, a `namedtuple` `codecademyStudent` with two fields (`username` and `courses`) to create two student instances is created. Two sentences will then be displayed about each student and their attributes. |
| 104 | +# Use _make() to create instances |
| 105 | +coord1 = Coordinate._make(point_list) |
| 106 | +coord2 = Coordinate._make(point_tuple) |
| 107 | + |
| 108 | +print(coord1) |
| 109 | +print(coord2) |
| 110 | +``` |
| 111 | + |
| 112 | +This example results in the following output: |
| 113 | + |
| 114 | +```shell |
| 115 | +Coordinate(x=10, y=20, z=30) |
| 116 | +Coordinate(x=5, y=15, z=25) |
| 117 | +``` |
| 118 | + |
| 119 | +### Example 3: Python Namedtuple `_asdict()` Method |
| 120 | + |
| 121 | +Converts a `namedtuple` instance to an OrderedDict, preserving the field names as keys and their corresponding values: |
41 | 122 |
|
42 | 123 | ```py |
43 | 124 | from collections import namedtuple |
44 | 125 |
|
45 | | -codecademyStudent = namedtuple('codecademyStudent', ['username', 'courses']) |
| 126 | +# Create namedtuple |
| 127 | +Student = namedtuple('Student', ['name', 'grade', 'subject']) |
| 128 | +student = Student('Alice Johnson', 95, 'Mathematics') |
46 | 129 |
|
47 | | -student1 = codecademyStudent(username='Foo', courses=['Python', 'Computer Science']) |
48 | | -student2 = codecademyStudent(username='Bar', courses=['Javascript', 'Web Development']) |
| 130 | +# Convert to dictionary |
| 131 | +student_dict = student._asdict() |
| 132 | +print("As dictionary:", student_dict) |
49 | 133 |
|
50 | | -print("Student 1:", "Username:", student1.username, "| Courses involvement:", student1.courses) |
51 | | -print("Student 2:", "Username:", student2.username, "| Courses involvement:", student2.courses) |
| 134 | +# Access dictionary values |
| 135 | +print("Name from dict:", student_dict['name']) |
| 136 | +print("Grade from dict:", student_dict['grade']) |
52 | 137 | ``` |
53 | 138 |
|
54 | | -The above example results in the following output: |
| 139 | +This example results in the following output: |
55 | 140 |
|
56 | 141 | ```shell |
57 | | -Student 1: Username: Foo | Courses involvement: ['Python', 'Computer Science'] |
58 | | -Student 2: Username: Bar | Courses involvement: ['Javascript', 'Web Development'] |
| 142 | +As dictionary: OrderedDict([('name', 'Alice Johnson'), ('grade', 95), ('subject', 'Mathematics')]) |
| 143 | +Name from dict: Alice Johnson |
| 144 | +Grade from dict: 95 |
59 | 145 | ``` |
60 | 146 |
|
61 | | -## Codebyte Example |
| 147 | +### Example 4: Namedtuple Using `**` (Double Star) Operator |
62 | 148 |
|
63 | | -The following example creates a `namedtuple` instance from an iterable, then changes one of its assigned values, and returns a [`dict`](https://www.codecademy.com/resources/docs/python/dictionaries) with the default preset values. |
| 149 | +Unpacks a dictionary or `namedtuple` to create new `namedtuple` instances using keyword arguments: |
64 | 150 |
|
65 | | -```codebyte/python |
| 151 | +```py |
66 | 152 | from collections import namedtuple |
67 | 153 |
|
68 | | -numbers = [0, 1, 2] |
69 | | -myNamedTuple = namedtuple('myNamedTuple', ['a', 'b', 'c']) |
70 | | -myNamedTuple_numbers = myNamedTuple._make(numbers) |
71 | | -
|
72 | | -print(myNamedTuple_numbers._fields) |
73 | | -print("---") |
74 | | -print(myNamedTuple_numbers) |
75 | | -print(myNamedTuple_numbers.c) |
76 | | -print(myNamedTuple_numbers._asdict()) |
77 | | -print("---") |
78 | | -print(myNamedTuple_numbers._replace(c=3)) |
| 154 | +# Create namedtuple class |
| 155 | +Product = namedtuple('Product', ['name', 'price', 'category']) |
| 156 | + |
| 157 | +# Create from dictionary using ** operator |
| 158 | +product_data = { |
| 159 | + 'name': 'Laptop', |
| 160 | + 'price': 999.99, |
| 161 | + 'category': 'Electronics' |
| 162 | +} |
| 163 | + |
| 164 | +laptop = Product(**product_data) |
| 165 | +print("Created from dict:", laptop) |
| 166 | + |
| 167 | +# Create from existing namedtuple using _replace (cleanest way) |
| 168 | +existing_product = Product('Phone', 599.99, 'Electronics') |
| 169 | +modified_product = existing_product._replace(price=549.99) |
| 170 | +print("Modified product:", modified_product) |
79 | 171 | ``` |
| 172 | + |
| 173 | +This example results in the following output: |
| 174 | + |
| 175 | +```shell |
| 176 | +Created from dict: Product(name='Laptop', price=999.99, category='Electronics') |
| 177 | +Modified product: Product(name='Phone', price=549.99, category='Electronics') |
| 178 | +``` |
| 179 | + |
| 180 | +## Frequently Asked Questions |
| 181 | + |
| 182 | +### 1. What is a `namedtuple` in Python? |
| 183 | + |
| 184 | +A `namedtuple` is a factory function in the `collections` module that creates tuple subclasses with named fields. It combines the immutability and memory efficiency of tuples with the readability of accessing elements by name rather than index. |
| 185 | + |
| 186 | +### 2. How do you create a `namedtuple` in Python? |
| 187 | + |
| 188 | +You create a `namedtuple` by calling `namedtuple(typename, field_names)` where `typename` is the class name and `field_names` is a list of field names. For example: `Person = namedtuple('Person', ['name', 'age'])`. |
| 189 | + |
| 190 | +### 3. What are the 4 collection data types in Python? |
| 191 | + |
| 192 | +The four main built-in collection data types in Python are: list (ordered and mutable), tuple (ordered and immutable), set (unordered and mutable with unique elements), and dict (ordered key-value pairs, mutable). The `collections` module provides additional specialized data types like `namedtuple`, `deque`, `Counter`, and `defaultdict`. |
0 commit comments