Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Adding Custom Column to Tuple list in Python
In this article, we will learn how to add a custom column to a list of tuples in Python. Tuples store sequences of data enclosed in parentheses, and when combined into lists, they can represent tabular data structures.
Understanding Tuple Lists
A single tuple looks like this:
(11, 22, 33)
A list of tuples represents tabular data:
[(11, 22, 33), (44, 55, 66), (77, 88, 99)]
Each tuple represents a row, and each position within the tuple represents a column. For example, a student database might look like:
Our goal is to add a new column (grades) to create:
Using zip() with List Comprehension
The zip() function pairs elements from multiple iterables. Combined with list comprehension, we can add a new column efficiently:
# List of students
students = [("Alice", 18), ("Bob", 17), ("Charlie", 16)]
# Grades to add as new column
grades = ("A", "B", "C")
# Adding custom column using zip() and list comprehension
students_with_grade = [(name, age, grade) for (name, age), grade in zip(students, grades)]
print(students_with_grade)
[('Alice', 18, 'A'), ('Bob', 17, 'B'), ('Charlie', 16, 'C')]
The zip() function pairs each tuple from students with each grade, then list comprehension unpacks and reconstructs them into new tuples.
Using map() Function
The map() function applies a function to corresponding elements of multiple iterables. We can use it with a lambda function to concatenate tuples:
# List of students
students = [("Alice", 18), ("Bob", 17), ("Charlie", 16)]
# Grades to add as new column
grades = ("A", "B", "C")
# Adding custom column using map() function
students_with_grade = list(map(lambda student, grade: student + (grade,), students, grades))
print(students_with_grade)
[('Alice', 18, 'A'), ('Bob', 17, 'B'), ('Charlie', 16, 'C')]
The lambda function takes each student tuple and grade, then concatenates them using + operator with (grade,) to create a singleelement tuple.
Comparison
| Method | Readability | Performance | Best For |
|---|---|---|---|
| zip() + List Comprehension | High | Fast | Simple column addition |
| map() + Lambda | Medium | Fast | Functional programming style |
Conclusion
Use zip() with list comprehension for readable code when adding columns to tuple lists. The map() function offers a functional approach that works well for simple transformations.
