1

I need some help with converting a list of equal sized lists x to a list of tuples such that each tuple should be the length of x

x = [
['4', '8', '16', '32', '64', '128', '256', '512', '1,024'], 
['1,200', '2,400', '4,800', '4,800', '6,200', '6,200', '6,200', '6,200', '6,200'], 
['300', '600', '1,200', '2,400', '3,200', '3,200', '4,000', '4,000', '4,000']
]
# some functions that converts it to 
expected_output = [('4', '1,200', '300'), ('8', '2,400', '600'), ...]

in this case len(x) is 3 but I want a function that can handle any length of x

User19
  • 101
  • 5
  • What should happen if you want len to be 3 but encounter sublist of length 7 i.e. not evenly divisble? – Daweo Jan 24 '22 at 08:12
  • @Daweo the lists inside x will always be of equal length, so if `len(x)` is 7 the tuple size will be 7 – User19 Jan 24 '22 at 08:14

2 Answers2

4

Use zip with unpacking operator *:

out = list(zip(*x))

Output:

[('4', '1,200', '300'),
 ('8', '2,400', '600'),
 ('16', '4,800', '1,200'),
 ('32', '4,800', '2,400'),
 ('64', '6,200', '3,200'),
 ('128', '6,200', '3,200'),
 ('256', '6,200', '4,000'),
 ('512', '6,200', '4,000'),
 ('1,024', '6,200', '4,000')]
  • works perfectly, Can I ask what does the *x exactly do and when is it useful? – User19 Jan 24 '22 at 08:25
  • @User19 `x` is a list of lists and `*` allows us to unpack them as `len(x)` separate lists. –  Jan 24 '22 at 08:33
2

How about this solution:

list(zip(*x))
Andrey
  • 400
  • 2
  • 8