JRR
JRR

Reputation: 6152

how to split tuples into two lists?

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

Upvotes: 3

Views: 1236

Answers (4)

Bernardo stearns reisen
Bernardo stearns reisen

Reputation: 2657

I would do something like this:

def foo(i):
    return (i,i+1)
r1, r2 = [tpl for tpl in zip(*map(foo,range(10)))]

Upvotes: 2

Ali Hassan
Ali Hassan

Reputation: 966

You just need to do this simple

r1, r2 = map(list, zip(*foo))

Upvotes: 5

Amitai Irron
Amitai Irron

Reputation: 2055

def foo(i):
    return ("A%d" % i, "B%d" % i)

# This is the one-liner
[r1, r2] = map(list, zip(*(foo(i) for i in range(10))))

print(r1)
print(r2)

zip takes an M of sequences of N items, and returns N sequences of M items. By taking the sequence generated by the comprehension expression in the and putting a * before it, I convert it into 10 separate sequences of two elements. The mapping to list is just to make all results into lists.

Upvotes: 0

Samwise
Samwise

Reputation: 71434

This ought to do it:

r1, r2 = map(list, zip(*[foo(i) for i in range(10)]))

By passing a list of tuples as args to zip (using * to convert the list into a list of args), you can "unzip" them. Map the list function over the resulting tuples and you have your two lists.

Upvotes: 1

Related Questions