10

I'm a bit of a Python beginner so I apologise if this is a very basic question.

I have two lists of data which are obtained from:

with filein as f:
        reader=csv.reader(f)
        xs, ys = zip(*reader)

I would like to create a loop which would take the first item in "xs" and the first item in "ys" and print them out. I would then like to loop back and repeat for the second item in both lists and so forth.

I had thought something like:

for x in xs and y in ys:

Or

for x in xs:
    for y in ys:

But neither of these seems to give the desired result.

Artjom B.
  • 61,146
  • 24
  • 125
  • 222
user1813343
  • 175
  • 2
  • 3
  • 7

3 Answers3

15

Use the zip function, along with tuple unpacking:

for x, y in zip(xs, ys):
    print x, y

In your case, depending on what you need the xs and ys for, you could have iterated through the csv.reader directly:

with filein as f:
    reader=csv.reader(f)
    for x, y in reader:
        print x, y

The zip(xs, ys) line was effectively reversing your xs, ys = zip(*reader) line.

David Robinson
  • 77,383
  • 16
  • 167
  • 187
8

Use zip:

>>> L=[1,2,3]
>>> M=[4,5,6]
>>> for a,b in zip(L,M):
...   print(a,b)
...
1 4
2 5
3 6
Mark Tolonen
  • 166,664
  • 26
  • 169
  • 251
1

For a one line you can use combination of map() and lambda(). Look here if not familiar to this concepts.

But be careful, you must be with python 3.x so that print is a function and can be used inside the lambda expression.

>>> from __future__ import print_function
>>> l1 = [2,3,4,5]
>>> l2 = [6,7,3,8]
>>> list(map(lambda X: print(X[0],X[1]), list(zip(l1,l2))))

output

2 6
3 7
4 3
5 8
kiriloff
  • 25,609
  • 37
  • 148
  • 229
  • Not sure why this one was down voted, if its because the print statement is confusing them then use. list(map(lambda x: x, list(zip(l1,l2)))) – Hutch Jun 08 '21 at 17:50
  • To me it appears like OP is asking for all possible combinations rather than aligned pairs produced by yield. – M Ciel Sep 07 '22 at 16:52