0

How would I do following more efficiently without iterating twice through the zipped list:

x = [(item1['a'], item2) for item1, item2 in zip(foo, bar)]
y = [item2.replace(item1['b'], '') for item1, item2 in zip(foo, bar)]
1
  • 2
    Unless I'm missing something, just don't use list comprehension. Initialize x and y, then do the for loop with the zip. Inside of the one and only for loop, append to both x and y. Commented Aug 18, 2020 at 12:54

2 Answers 2

3

Slightly less Pythonic:

x = []
y = []
for item1,item2 in zip(foo,bar):
    x.append((item1['a'],item2))
    y.append(item2.replace(item1['b'],''))
Sign up to request clarification or add additional context in comments.

3 Comments

why is that less pythonic? :)
@Tomerikoo: it is just my opinion ;)
I just think people tend to get fixated on list-comps and sometimes (like this case) a good old-fashioned loop is more pythonic (simple is better than complex and all that...)
1

In general, you can use a generator expression to output multiple values as tuples and then zip the outputting sequence of tuples into individual sequences so that you can unpack them into separate variables.

So instead of, for example:

x = [i + 1 for i in lst]
y = [i + 2 for i in lst]

You can do:

x, y = zip(*((i + 1, i + 2) for i in lst))

In this case x and y will become tuples, however, so if you need x and y to be actual lists instead you can map the outputting sequence to the list constructor:

x, y = map(list, zip(*((i + 1, i + 2) for i in lst)))

So the statements in your question can be rewritten as:

x, y = map(list, zip(*(((item1['a'], item2), item2.replace(item1['b'], '')) for item1, item2 in zip(foo, bar))))

1 Comment

These come out as tuples rather than lists.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.