-1

I come from tcl/tk, and am trying to do the following in python:

for a,b in [1,2,3,4,5,6]:
   print a,b

with the desired output

1,2
3,4
5,6

This is quite common in tcl/tk, but I can't figure out how to get python to do it.

3 Answers3

0

You can use iter() and next() functions.

list = [1,2,3,4,5,6,7,8,9,10]
it = iter(list)
for x in it:
   print (x, next(it))

Output:

1 2
3 4
5 6
7 8
9 10
TaQuangTu
  • 2,155
  • 2
  • 16
  • 30
0

You can use this code:

ls =[1,2,3,4,5,6]
a = ls[::2]
b = ls[1::2]

for i,j in zip(a,b) :
    print(i,j)
Surya Lohia.
  • 446
  • 4
  • 16
0

You can do that.

Adjust the value of group_size to the number of elements you want for your tuples.

the_list =  [1,2,3,4,5,6]
group_size = 2
result = list(zip(*(iter(the_list),) * group_size))
print(result)

Output:

[(1, 2), (3, 4), (5, 6)]

And for your desired output:

for a,b in result:
    print(str(a) + "," + str(b))

Output:

1,2
3,4
5,6
Rivers
  • 1,783
  • 1
  • 8
  • 27