Use zip
and slices
>>> for i,j in zip(en[::2],en[1::2]):
... print("{}{}".format(i,j))
...
12
34
56
As Steven Rumbalski mentions in a comment you can also do
>>> it = iter(en)
>>> for i,j in zip(it, it):
... print i,j
...
1 2
3 4
5 6
it
here is an iterator over the list. Hence it gives out the next value in the list whenever it’s next
method is called. Once the end is reached, it raises an exception (StopIteration) after which the iteration stops. The zip
internally calls next
of the iterator. Hence everytime it returns two adjacent values together, as you are calling the same object. In this way we can get the desired output.
2
solved How to perform this printing in for loop?