0
x=[1,2,3,4,5]
y=[6,7,8,9,10]
for a,b in x,y:
    print(a,b)

expected output:

1,6
2,7
3,8
4,9
5,10

But I know two count variables are not possible. Help me by giving better alternative code to achieve the same.

Ch3steR
  • 20,090
  • 4
  • 28
  • 58
Vishnu Vardhan
  • 47
  • 1
  • 1
  • 6

3 Answers3

2

You can use the zip() function. The zip() function returns a zip object, which is an iterator of tuples where the first item in each passed iterator is paired together, and then the second item in each passed iterator are paired together etc.

Try this:

x=[1,2,3,4,5] 
y=[6,7,8,9,10]

for a, b in zip(x, y):
    print(f"{a}, {b}")

Output:

1, 6
2, 7
3, 8
4, 9
5, 10
Shubham Sharma
  • 68,127
  • 6
  • 24
  • 53
2

You can use zip here.

for a,b in zip(x,y):
    print(a,b,sep=', ')

Using range

for i in range(len(x)):
    print(x[i],y[i],sep=', ')

If you have unequal length list use itertools.zip_longest.

for i,j in itertools.zip_longest(x,y,fillvalues=' '):
    print(i,j,sep=', ')
Ch3steR
  • 20,090
  • 4
  • 28
  • 58
1

Use zip and format the output:

x = [1, 2, 3, 4, 5]
y = [6, 7, 8, 9, 10]

str_ = ""
for x_, y_ in zip(x,y):
    str_ += "%d,%d " % (x_, y_)

print(str_)

Output:

1,6 2,7 3,8 4,9 5,10

Also:

for x_, y_ in zip(x,y):
    print("%d,%d" % (x_, y_))

Output:

1,6
2,7
3,8
4,9
5,10
Chicodelarose
  • 827
  • 7
  • 22