Trevor Smith
Trevor Smith

Reputation: 1

How to iterate a zip list and print each index of it after joining to lists of the same size?

Given the variables:

X = ['a', 'b', 'c']
Y = [1, 2, 3]

complete the following statement:

[print(pair) for pair in ...] 

so as to print to the screen pairs of elements from X and Y which occupy the same position in the index.

I know I can make a join X and Y and make a list using list(zip(X,Y)) but the adding that in the statement gives an empty list.

I can't solve this problem using the form required any help?

thanks!

Upvotes: 0

Views: 137

Answers (2)

Patrick Artner
Patrick Artner

Reputation: 51683

Using list comprehensions to leverage a sideeffect (like printing something) is frowned upon. If you dont need a list, don't build one.

[print(pair) for pair in zip(X,Y)]  # no need to list(zip(...))

will result in lots on None ... because the return value of print() is None.

Use a simple loop:

for p in zip(X,Y):
    print(p)

Upvotes: 1

Slam
Slam

Reputation: 8572

Not really clear what you're trying to achieve. If you need to print pairs, zip works, i.e.

for pair in zip(X, Y):
    print(pair)

[print(pair) for pair in ...] is list comprehension, this is made to create lists, not to print data:

pairs_list = [pair for pair in zip(X, Y)]  # don't do this

which is simply pairs_list = list(zip(X, Y)). Does this make sense to you?

Upvotes: 1

Related Questions