Search code examples
pythonlistindexinglist-comprehensionsublist

python - is there a way to use list comprehension to create a list based on the extracted common indexes of sublists?


I am trying to figure out a clean way to get the elements at the same index of each sublist and create a new list based on those extracted elements, so first I would like a sublist containing element 0 of each earlier sublist, then same the same for element 1, 2 etc. At the moment I am using the following code to get the results I want:

lst = [[1, 2, 3, 4], ['a', 'b', 'c', 'd'], [True, True, False, True], [14.5, 15.6, 12.5, 12.3]]
approach_1 = []

for i, item in enumerate(lst[0]):
    approach_1.append([item, lst[1][i], lst[2][i], lst[3][i]])

which gives me

approach_1 = [[1, 'a', True, 14.5], [2, 'b', True, 15.6], [3, 'c', False, 12.5], [4, 'd', True, 12.3]]

The results are what I am looking for but is there a way for me to achieve this in one line? I am able to use the following for one element:

approach_2 = [x[0] for x in lst] 

Is there anything similar to this that would return the same results as approach_1?


Solution

  • The built-in zip function does exactly what you want:

    >>> lst = [[1, 2, 3, 4], ['a', 'b', 'c', 'd'], [True, True, False, True], [14.5, 15.6, 12.5, 12.3]]
    >>> list(zip(*lst))
    [(1, 'a', True, 14.5), (2, 'b', True, 15.6), (3, 'c', False, 12.5), (4, 'd', True, 12.3)]