1

I am trying iterate over a list, two at a time. This is my code:

list_1 = [1,3,2,4,3,1,2,7]

The ouput should be like this(the iteration should start from the first element):

1
2
3
2

Seven, is not there because the iteration in only 2.

This is my try:

nums = [1,3,2,4,3,1,2,7]
for x, y in zip(*[iter(nums)]*2):
    print(x, y)

But my output is:

1 3
2 4
3 1
2 7

How can I achieve the proper iteration using Python 3?

Mahir
  • 400
  • 3
  • 15
  • 5
    Hmm... Does something like `for e in list_1[::2]` work similar to what you are looking for? – Norrius Jun 17 '18 at 23:26
  • Why not just `print(x)` in your try? – AChampion Jun 17 '18 at 23:32
  • I added the last question to the duplicate list because since you're just printing elements here, you might consider using [`itertools.islice`](https://docs.python.org/3/library/itertools.html#itertools.islice) to avoid copying your list if it is large. – miradulo Jun 17 '18 at 23:37

1 Answers1

2

You can use range like this by using step (indexing):

list_1 = [1,3,2,4,3,1,2,7]

for i in range(0,len(list_1),2):
    print(list_1[i])

or just using python slice notation:

list_1 = [1,3,2,4,3,1,2,7]

for v in list_1[::2]:
    print(v)
BPL
  • 9,632
  • 9
  • 59
  • 117