Siddharth Kumar
Siddharth Kumar

Reputation: 134

Extend separate lists with the outputs of a function

I was wondering if there was a more elegant way of doing the following:

EDIT:

def whaa(x):
    # Let's not get too picky about this function
    return list(range(0,x)), list(range(-1,x))

a, b = whaa(10)
c = whaa(20)
a.extend(c[0])
b.extend(c[1])

EDIT: The behavior of the function is dependent on the input. And I want the corresponding outputs to go neatly into the same list.

Essentially, what I want to do is access the individual elements of the output tuple and extend my lists without going through the trouble of storing the output into a separate variable. It seems like given this construct, it's not something that's possible but I'm open to suggestions!

Upvotes: 0

Views: 40

Answers (2)

akuiper
akuiper

Reputation: 214927

Use a for loop to extend each element of the returned tuple:

a, b = tuple(x * 2 for x in whaa())

a
# [1, 2, 3, 1, 2, 3]

b
# [2, 3, 4, 2, 3, 4]

For the updated question, you can use zip as the answer of @John:

a, b = tuple(x + y for x, y in zip(whaa(10), whaa(20)))

Upvotes: 2

John La Rooy
John La Rooy

Reputation: 304137

You can do it like this:

for x, y in zip([a, b], c):
    x.extend(y)

But then why have you not just left a and b in a list in the first place?

c = whaa(10)
for x, y in zip(c, whaa(20)):
    x.extend(y)
a, b = c                       # save unpacking until the end

Upvotes: 2

Related Questions