7
\$\begingroup\$

Can you improve?

rc = []
for i, j in zip(A_response, B_response):
    rc.append(i)
    rc.append(j)

I use zip and append, but could this be better using list comprehension?

\$\endgroup\$
7
\$\begingroup\$

A good solution is in this Stack Overflow answer:

rc = [response for ab in zip(A_response, B_response) for response in ab]
\$\endgroup\$
3
\$\begingroup\$

Note that zip will not use excess elements when one list is longer than the other. For example, if one of the lists is empty and the other is not, your program will result in an empty list. I'm not sure if this was your intention. If it wasn't, then you might want to extend the result list with the excess elements of the longer list.

As @MrGrj pointed out in a comment:

You could use izip_longest for Python < 3 or zip_longest for Python >= 3. Both come from itertools module.

\$\endgroup\$
  • 1
    \$\begingroup\$ You could mention izip_longest()for python < 3 or zip_longest() for python >= 3. Both come from itertools module. \$\endgroup\$ – яүυк Jun 2 '17 at 7:36

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.