Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to split tuples into two lists?

Tags:

python

The function foo below takes in a number and returns a tuple of strings. Can I write the following loop as a one-liner?

r1 = []
r2 = []
for i in range(10):
  (s1, s2) = foo(i)
  r1.append(s1)
  r2.append(s2)

# r1 now has the first returned strings from each iteration of the loop, and similarly for r2
like image 405
JRR Avatar asked Mar 09 '26 03:03

JRR


2 Answers

You just need to do this simple

r1, r2 = map(list, zip(*foo))
like image 198
Ali Hassan Ahmed Khan Avatar answered Mar 11 '26 16:03

Ali Hassan Ahmed Khan


I would do something like this:

def foo(i):
    return (i,i+1)
r1, r2 = [tpl for tpl in zip(*map(foo,range(10)))]
like image 27
Bernardo stearns reisen Avatar answered Mar 11 '26 17:03

Bernardo stearns reisen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!