Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
iterating a span of a list
#4
import itertools
from functools import partial


def window(sequence, window_size, uncomplete=True, fillvalue=None):
    if uncomplete:
        izip = partial(itertools.zip_longest, fillvalue=fillvalue)
    else:
        izip = zip
    yield from izip(*[iter(sequence)] * window_size)
l = list(range(10))
for chunk in window(l, 3):
    print(chunk)
Output:
(0, 1, 2) (3, 4, 5) (6, 7, 8) (9, None, None)
If you use uncomplete=False, the zip function will be used.
The zip function stops iterating, if there are not enough values, to fill the window.

l = list(range(10))
for chunk in window(l, 3, uncomplete=False):
    print(chunk)
Output:
(0, 1, 2) (3, 4, 5) (6, 7, 8)
Almost dead, but too lazy to die: https://sourceserver.info
All humans together. We don't need politicians!
Reply


Messages In This Thread
iterating a span of a list - by Skaperen - Dec-29-2019, 12:06 AM
RE: iterating a span of a list - by Gribouillis - Dec-29-2019, 12:14 AM
RE: iterating a span of a list - by Skaperen - Dec-29-2019, 07:40 AM
RE: iterating a span of a list - by DeaD_EyE - Dec-29-2019, 08:54 AM
RE: iterating a span of a list - by Gribouillis - Dec-29-2019, 10:08 AM
RE: iterating a span of a list - by Skaperen - Dec-29-2019, 08:15 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Delete list while iterating shantanu97 1 1,919 Jun-06-2021, 11:59 AM
Last Post: Yoriz
  Creating a list of dictionaries while iterating pythonnewbie138 6 3,342 Sep-27-2020, 08:23 PM
Last Post: pythonnewbie138
  python3: iterating through list not working wardancer84 3 2,384 Jul-08-2020, 04:30 PM
Last Post: DPaul
  Indexing problem while iterating list and subtracting lbtdne 2 2,160 May-14-2020, 10:19 PM
Last Post: deanhystad
  Here what is the meaning of span=(1,2) ,match='1'? srisrinu 1 2,143 Apr-27-2020, 10:22 AM
Last Post: anbu23
  Iterating through a list of strings Ash_Ren 1 2,119 Nov-22-2019, 08:30 PM
Last Post: buran
  Span columns with docxTemplate python jimmeh 4 4,360 May-29-2019, 04:40 PM
Last Post: heiner55
  iterating a list of ranges Skaperen 1 2,059 May-22-2019, 07:44 AM
Last Post: Gribouillis
  Iterating list of oredereddict for creating new list of ordereddict babypython 7 3,749 May-05-2019, 05:32 PM
Last Post: Larz60+
  Efficient way of iterating a list of records anguis 4 3,095 Feb-19-2019, 03:39 AM
Last Post: scidam

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020