0

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?

user3153443
  • 511
  • 3
  • 6
  • 13

4 Answers4

1

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)]
Asocia
  • 5,935
  • 2
  • 21
  • 46
1

A solution with list comprehension:

[list(i) for i in zip(*lst)]

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

Or, using map

list(map(list, zip(*lst)))

will give you same result

englealuze
  • 1,445
  • 12
  • 19
0

You can write two for loops in one line!

new_list = [[j[i] for j in lst] for i in range(0, len(lst[0]))]
maede rayati
  • 756
  • 5
  • 10
0
list( zip( lst[0], lst[1], lst[2], lst[3] ) )

or if you want each element to be a list instead of a tuple, you can do this

result = [ list(x) for x in list( zip( lst[0], lst[1], lst[2], lst[3] ) ) ]
saiffarid
  • 43
  • 1
  • 2
  • 9
  • 1
    This requires to know the length of lst beforehand. Python syntax * for unpacking is a good trick, check other solutions for example – englealuze May 28 '20 at 21:27