0

Simplest way to iterate in pairs or more in python over a single list?

list1=['Hello ','World','.','I ','heart ','python']

Something like this:

for x,y,z in list1:
    print x,y,z

What I would like to get as a result:

Hello World.

I heart python

I know I can do it like this but I would like to know if there is something that doesn't require index counting. Preferably using a for loop.

index=0
while index<len(list1):
     print list1[index],list1[index+1],list1[index+2]
     index+=3
Community
  • 1
  • 1

2 Answers2

0

The easiest way would be to use zip to turn your list into a list of tuples, and then u can iterate over that:

list1 = zip(list1[0::2], list1[1::2])
for elem1, elem2 in list1:
   print elem1, elem2
TheoretiCAL
  • 19,461
  • 8
  • 43
  • 65
0

Not sure how more or less pythonic this is but

for x, y, z in zip(list1[::3],list1[1::3], list1[2::3]):
  print x+y+z
dloman
  • 142
  • 5