How to Create a List of Tuples in Python [6 Methods + Examples]

In this Python tutorial, I will explain how to create a list of tuples in Python using different methods with some illustrative examples. I will also explain how to take the list of tuples as input in Python.

Tuples in Python are immutable sequences that can store multiple items in an ordered way. Lists in Python, on the other hand, are ordered, mutable sequences. Together, lists and tuples are powerful structures in Python that are commonly used for data organization. This article will delve into various methods to create a list of tuples in Python.

Methods to create a list of tuples in Python

There are many different methods to create a list of tuples in Python:

  1. Using square[] and parenthesis()
  2. Using List Comprehension
  3. Using the zip() Function
  4. Using the map() Function
  5. From Dictionary
  6. Nested Loops

Let’s see them one by one with some demonstrative examples:

Note: To check whether the thing that we have created is a list of tuples in Python or not, we will use the type() function. First, we will check the outer part and then the elements inside it.

Method 1: Python list of tuples using square[] and parenthesis()

This is the most basic method where we directly define a list containing tuples using square[] and parenthesis() in Python. This approach is suitable when we have a small, fixed set of tuple values in Python.

Example: Manually we are creating a Python list using [] brackets, and crafting a tuple using () inside that list.

states_with_dates = [('California', 1850), ('Texas', 1845), ('Florida', 1845)]
print(states_with_dates)
print(type(states_with_dates))
print(type(states_with_dates[0]))

Output: Here, we’ve directly hard-coded a list of tuples in Python.

[('California', 1850), ('Texas', 1845), ('Florida', 1845)]
<class 'list'>
<class 'tuple'>
list of tuples in Python

This way we can use the square brackets[], and parenthesis() to make a list of tuples in Python manually.

READ:  How to Create a String with Double Quotes in Python

Method 2: List of tuples in Python using the zip() function

The zip() function is used for pairing the respective elements from two or more iterables. It returns an iterator of tuples.

When we have two lists of equal length in Python and we want to pair the elements at each respective index, zip() is the direct choice. The output is then type-casted to a Python list, giving us a list of tuples in Python.

Example: In this case, we are using the zip() function that pairs all the elements from two or more Python lists, as the list of tuples in Python.

states = ['California', 'Texas', 'Florida']
capitals = ['Sacramento', 'Austin', 'Tallahassee']
states_with_capitals = list(zip(states, capitals))
print(states_with_capitals)
print(type(states_with_capitals))
print(type(states_with_capitals[0]))

Output: Here, we are first creating tuples with the help of the zip() function using the elements of each list and then we transform them into a Python list using the list() type cast.

[('California', 'Sacramento'), ('Texas', 'Austin'), ('Florida', 'Tallahassee')]
<class 'list'>
<class 'tuple'>
create list of tuples python

This way we can use the zip() function to create Python tuples and the list() function to create the list in Python.

Method 3: List of tuples Python using list comprehension

List comprehensions are one of Python’s most beloved features. They offer a syntactically elegant way to create lists by performing some operation on each item in an existing list in Python (or other iterables).

Scenario: Here, when we combine the list comprehension with the zip() function, we can take two lists in Python (numbers and letters in our case) and iterate over their combined elements, effectively forming a Python tuple for each pair of elements.

states = ['California', 'Texas', 'New York']
time_zones = ['Pacific', 'Central', 'Eastern']
state_time_zones = [(state, zone) for state, zone in zip(states, time_zones)]
print(state_time_zones)
print(type(state_time_zones))
print(type(state_time_zones[0]))

Output: Here, List comprehension is a concise way to create lists in Python. Combined with the zip() function, it pairs each element from one list with its respective elements of other Python lists.

[('California', 'Pacific'), ('Texas', 'Central'), ('New York', 'Eastern')]
<class 'list'>
<class 'tuple'>
how to create a list of tuples in python

This way we can use list comprehension with the zip() function to create a list of tuples in Python.

Method 4: Create list of tuples in Python using the map() function

The map() function applies a given function to all items in an input list in Python. When used for our purpose, the applied function essentially creates a tuple from the input elements.

READ:  Lambda in List Comprehension in Python [3 Examples]

Using the map() function with a Python function (which simply returns a tuple of its arguments) allows us to process two lists simultaneously and generate the desired list of tuples in Python.

Scenario: Once again we have two different lists in Python and we have to create a list of tuples in Python using the map() function.

states = ['Alaska', 'California', 'Texas']
areas = [663267, 163696, 268596]
state_area_tuples = list(map(lambda state, area: (state, area), states, areas))
print(state_area_tuples)
print(type(state_area_tuples))
print(type(state_area_tuples[0]))

Output: The map() function applies a function to all items in the input list(s) in Python. Here, a lambda function creates tuples pairing elements of one list with their respective elements of another Python list.

[('Alaska', 663267), ('California', 163696), ('Texas', 268596)]
<class 'list'>
<class 'tuple'>
how to create list of tuples in python

The map() function with the lambda function can create tuples and list() to create a list in Python.

Method 5: Python create a list of tuples from dictionary

Dictionaries in Python inherently store data as key-value pairs. The items() method of a dictionary returns a set-like object providing a view on its items, i.e., key-value pairs in Python.

Using the list(dictionary.items()), we can easily obtain a list of key-value pairs as tuples in Python.

Example: Consider a situation where we have a dictionary in Python, and have to convert them into a list of tuples in Python.

state_population = {'California': 39538223, 'Texas': 29145505, 'Florida': 21538187}
population_tuples = list(state_population.items())
print(population_tuples)
print(type(population_tuples))
print(type(population_tuples[0]))

Output: Dictionaries store data as key-value pairs. Using the items() method, we can retrieve these pairs as tuples. And, we use the list() type cast in Python to create the Python list.

[('California', 39538223), ('Texas', 29145505), ('Florida', 21538187)]
<class 'list'>
<class 'tuple'>
how to make a list of tuples

The dictionary in Python has many different methods like items() that can help us to create a list of tuples in Python.

Method 6: Create a list of tuples in Python using nested loops

Nested loops mean using one loop inside another, which results in the inner loop running its full course for every single iteration of the outer loop in Python.

If we need to pair each element of one list in Python with every element of another (forming a cartesian product), then nested loops (or list comprehension with nested loops) become useful in Python.

Scenario: Consider a situation where we have given two different lists of Python, and only have to use loops to convert them into a list of tuples in Python.

states = ['New York', 'California']
landmarks = ['Statue of Liberty', 'GG Bridge']
tour_packages = [(state, landmark) for state in states for landmark in landmarks]
print(tour_packages)
print(type(tour_packages))
print(type(tour_packages[0]))

Output: The nested list comprehension with loops iteratively combines elements from two lists in Python. Here, each item from one list is paired with each item from another list in Python.

[('New York', 'Statue of Liberty'), ('New York', 'GG Bridge'), ('California', 'Statue of Liberty'), ('California', 'GG Bridge')]
<class 'list'>
<class 'tuple'>
how to make a list of tuples in python

This way we can use the nested loops in list comprehension to create a list of tuples in Python.

READ:  Python dictionary update() method [With Examples]

How to take List of Tuples as input in Python

To take a list of tuples as input in Python, we can use the input() function and then process the input to convert it into a list of tuples in Python.

Here’s a step-by-step approach:

1. Get the number of tuples you want to input.

2. For each tuple, get the elements and then convert them to the desired type (e.g., int or float). Otherwise, it will be in string data type in Python.

3. Add each tuple to the list in Python.

Example: Let’s take an example, of how we can take input from a user and create a list of tuples in Python using the input() function.

n = int(input("Enter the number of participating cities: "))
city_data = []
for _ in range(n):
    data_str = input(f"Enter data for city {_ + 1} (format: 'City Name,Expected Participants,Estimated Funds'): ")
    split_data = data_str.split(',')
    city_name = split_data[0].strip()
    expected_participants = int(split_data[1].strip())
    estimated_funds = int(split_data[2].strip())
    city_data.append((city_name, expected_participants, estimated_funds))
print("\nCity Data:", city_data)

Output:

Enter the number of participating cities: 3
Enter data for city 1 (format: 'City Name,Expected Participants,Estimated Funds'): New York,2,400
Enter data for city 2 (format: 'City Name,Expected Participants,Estimated Funds'): Texas,5,1000
Enter data for city 3 (format: 'City Name,Expected Participants,Estimated Funds'): California,3,600

City Data: [('New York', 2, 400), ('Texas', 5, 1000), ('California', 3, 600)]
how to take list of tuples as input in python

Conclusion

This Python explains how to create a list of tuples in Python using six different methods like manually, list comprehension, the zip() function, the map() function, using methods from dictionary, or nested for loop with illustrative examples. I have also explained how to take a list of tuples as input in Python with an example.

You may also like to read some of our Python articles: