How to Create a List of Tuples in Python
To create a list of tuples in Python, you can use [] square brackets along with () parentheses or use the append() function.
The following examples show how to create a list of tuples using two different methods.
Using [] Square Bracket and () Parentheses
We can use [] square brackets and () parentheses to create a list of tuples.
Suppose we have the following data:
# Create list of tuples
emp_data = [
("A-12", "11/12/2021", "Anita", 2, "R&D", 25),
("B-45", "15/04/2017", "Sanika", 5, "Production", 27),
("C-78", "28/01/2003", "Shubham", 10, "Maintenance", 45),
("D-102", "1/9/2010", "Gaurav", 7, "HR", 36),
("E-96", "12/5/2022", "Namita", 1, "Marketing", None),
("F-53", "19/02/2008", "Sushma", 8, None, 30),
("A-12", "11/12/2021", "Anita", 2, "R&D", 25)
]
# Show list of tuples
print(emp_data)
Output: 👇️
[('A-12', '11/12/2021', 'Anita', 2, 'R&D', 25), ('B-45', '15/04/2017', 'Sanika', 5, 'Production', 27), ('C-78', '28/01/2003', 'Shubham', 10, 'Maintenance', 45), ('D-102', '1/9/2010', 'Gaurav', 7, 'HR', 36), ('E-96', '12/5/2022', 'Namita', 1, 'Marketing', None), ('F-53', '19/02/2008', 'Sushma', 8, None, 30), ('A-12', '11/12/2021', 'Anita', 2, 'R&D', 25)]
In this example, we use [] square brackets and () parentheses to create a list of tuples emp_data. The output shows the list of tuples created using [] square brackets and () parentheses.
Using append() Function
We can use the append() function to create a list of tuples.
Suppose we have the following data:
# Create empty list of tuples
emp_data = []
# Add tuples to list
emp_data.append(("A-12", "11/12/2021", "Anita", 2, "R&D", 25))
emp_data.append(("B-45", "15/04/2017", "Sanika", 5, "Production", 27))
emp_data.append(("C-78", "28/01/2003", "Shubham", 10, "Maintenance", 45))
# Show list of tuples
print(emp_data)
Output: 👇️
[('A-12', '11/12/2021', 'Anita', 2, 'R&D', 25), ('B-45', '15/04/2017', 'Sanika', 5, 'Production', 27), ('C-78', '28/01/2003', 'Shubham', 10, 'Maintenance', 45)]
In this example, we use the append() function to add tuples to the list emp_data.
The output shows the list of tuples created using the append() function.
Conclusion
We can use [] square brackets along with () parentheses or the append() function to create a list of tuples in Python.