0

If I have a list like l=[1,2,3,4,5,6]. If I do something like:

for i in l:
    print(i)

It will print all element separately.

1
2
3
4
.
.
.

Is there a way to iterate simultaneously over multiple elements?

For example, if I want to iterate over each 3 elements

for ....:
    print(..)

Should print:

1,2,3
4,5,6

So that in each iteration the variable that iterate the for will be a tuple of, in this case, 3 elements.

Chris
  • 26,361
  • 5
  • 21
  • 42
Will
  • 1,619
  • 5
  • 23

2 Answers2

4

Iterate over indices, and step three at a time, then use a slice within the loop to get the desired values.

>>> l=[1,2,3,4,5,6]
>>> for i in range(0, len(l), 3):
...   print(l[i:i+3])
...
[1, 2, 3]
[4, 5, 6]
>>>
Chris
  • 26,361
  • 5
  • 21
  • 42
  • 1
    Note that this method works also for lists whose length is not divisible by the length of the slice. For example, for `l = [1, 2, 3, 4]`, it will print `[1, 2, 3] [4]` – Timur Shtatland Dec 05 '22 at 15:53
0

To get exactly the required output you could do this:

lst = [1, 2, 3, 4, 5, 6]

for i in range(0, len(lst), 3):
    print(*lst[i:i+3], sep=',')

Output:

1,2,3
4,5,6
DarkKnight
  • 19,739
  • 3
  • 6
  • 22