1

Let's say I have a list:

n1 = [20, 21, 22, 23, 24]

and I want to iterate through the list and print the first three elements, then the next three elements of the sequence, up to the end. That is, I want this to be output:

20, 21, 22

21, 22, 23

22, 23, 24

How can I do this efficiently in Python?

StatsSorceress
  • 3,019
  • 7
  • 41
  • 82

3 Answers3

0

You can try this:

n1 = [20, 21, 22, 23, 24]
listing = [', '.join(map(str, n1[i:i+3])) for i in range(len(n1)-2)]
for l in listing:
  print(l)

Output:

20, 21, 22
21, 22, 23
22, 23, 24
Ajax1234
  • 69,937
  • 8
  • 61
  • 102
0

One way is to chunk your list and print. A generator function helps make this efficient, explicit and adaptable. Courtesy of @Ned Batchelder (upvote there).

def chunks(l, n):
    """Yield successive n-sized chunks from l."""
    for i in range(0, len(l) - (n-1)):
        yield l[i:i + n]

n1 = [20, 21, 22, 23, 24, 25]

for lst in chunks(n1, 3):
    print(' '.join(map(str, lst)))

# 20 21 22
# 21 22 23
# 22 23 24
# 23 24 25
jpp
  • 159,742
  • 34
  • 281
  • 339
0

If you only want to print out chunks of length 3, you can use zip() here:

n1 = [20, 21, 22, 23, 24]

for x, y, z in zip(n1, n1[1:], n1[2:]):
    print(x, y, z)

Which Outputs:

20 21 22
21 22 23
22 23 24

If you want to print out any sized chunks, you can use collections.deque:

from collections import deque
from itertools import islice

def chunks(lst, n):
    queue = deque(lst)

    while len(queue) >= n:
        yield list(islice(queue, 0, n))
        queue.popleft()

n1 = [20, 21, 22, 23, 24]

for x in chunks(n1, 3):
    print(*x)

# 20 21 22
# 21 22 23
# 22 23 24
RoadRunner
  • 25,803
  • 6
  • 42
  • 75