![]() |
Managing data often entails working with tuples of information, particularly when working with datasets. For more easy processing, these tuples can sometimes need to be split up into numerous lists. In this article, we will see how to convert list of tuples to multiple lists in Python. Convert List of Tuples to Multiple Lists in PythonBelow are some of the ways by which we can convert a list of tuples into multiple lists in Python: Convert List of Tuples to Multiple Lists Using map FunctionIn this example, the code transforms a list of tuples into two separate lists using map() and zip(). It creates ‘list1’ containing the first elements of the tuples and ‘list2’ containing the second elements, then prints both lists. Python3
Output
List 1: [1, 2, 3] List 2: ['a', 'b', 'c'] Convert List of Tuples to Multiple Lists Using Iterative UnpackingIn this example, the code employs iterative unpacking to transform a list of tuples into two separate lists. It iterates through each tuple, unpacks its elements into ‘val1’ and ‘val2’, and appends them to ‘list1’ and ‘list2’ respectively, then prints both lists. Python3
Output
List 1: [1, 2, 3] List 2: ['a', 'b', 'c'] Convert List of Tuples to Multiple Lists Using zip() FunctionIn this example, the code unpacks a list of tuples using `zip` and separates the elements into three lists: ‘numbers’ containing the first elements, ‘letters’ containing the second elements, and ‘booleans’ containing the third elements. The resulting lists are then printed. Python3
Output
Numbers: [1, 2, 3] Letters: ['a', 'b', 'c'] Booleans: [True, False, True] Converting List of Tuples with Different Lengths Using zip_longest() FunctionIn this example, the code uses Python3
Output
Numbers: [1, 2, 3] Letters: ['a', 'b', 'c'] Booleans: [None, True, False] Extra: [(None, None, 'extra')] ConclusionIn Python, converting a list of tuples to several lists is a simple operation; the method used will rely on readability and personal taste. The given examples demonstrate many approaches to get the intended result, allowing for flexibility in execution. |
Reffered: https://www.geeksforgeeks.org
Python |
Type: | Geek |
Category: | Coding |
Sub Category: | Tutorial |
Uploaded by: | Admin |
Views: | 11 |