Hey, readers! In this article, we will be focusing on Python List of Tuples.
What is Python List and Tuple?
Python List is a data structure that maintains an ordered collection of mutable data elements.
The elements in the list are enclosed within square brackets [].
Python Tuple is an immutable data structure whose elements are enclosed within parenthesis ().
Python List of Tuples
We can create a list of tuples i.e. the elements of the tuple can be enclosed in a list and thus will follow the characteristics in a similar manner as of a Python list. Since, Python Tuples utilize less amount of space, creating a list of tuples would be more useful in every aspect.
Example:
Output:
Python list of tuples using zip() function
Python zip() function can be used to map the lists altogether to create a list of tuples using the below command:
The zip() function returns an iterable of tuples based upon the values passed to it. And, further, the list() function would create a list of those tuples as an output from the zip() function.
Example:
Output:
Customized grouping of elements while forming a list of tuples
While forming a list of tuples, it is possible for us to provide customized grouping of elements depending on the number of elements in the list/tuple.
List comprehension along with zip() function is used to convert the tuples to list and create a list of tuples. Python iter() function is used to iterate an element of an object at a time. The number would specify the number of elements to be clubbed into a single tuple to form a list.
Example 1:
In the above example, we have formed a list of tuples with a single element inside a tuple using the iter() method.
Output:
Example 2:
In this example, two elements are contained inside a tuple to form a list of tuple.
Output:
Python list of tuples using map() function
Python map function can be used to create a list of tuples. The map() function maps and applies a function to an iterable passed to the function.
Example:
In this example, we have mapped the input list to the tuple function using map() function. After this, the list() function is used to create a list of the mapped tuple values.
Output:
Python list of tuples using list comprehension and tuple() method
Python tuple() method along with List Comprehension can be used to form a list of tuples.
The tuple() function helps to create tuples from the set of elements passed to it.
Example:
Output:
Conclusion
By this, we have come to the end of the article. I hope you all have enjoyed learning this interesting concept of Python list of tuples.
Feel free to comment below, in case you come across any doubt.
References
- Creating a list of tuples StackOverflow