Search code examples
python-3.xsliceenumerate

How to use enumerate and slicing together


The following is the normal usage of enumerate for the case that i want to have every 10 items:

for index, value in enumerate(range(50)):
    if index % 10 == 0:
        print(index,value)

Output:

0 0
10 10
20 20
30 30
40 40

now imagine i want to have output as:

1 1
11 11
21 21
31 31
41 41

or

2 2
12 12
22 22
32 32
42 42

How I can do that?


Solution

  • Not sure why you are doing it this way but you can just subtract n from index in the test, e.g.:

    In []:
    n = 1
    for index, value in enumerate(range(50)):
        if (index-n) % 10 == 0:
            print(index,value)
    
    Out[]:
    1 1
    11 11
    21 21
    31 31
    41 41
    

    Just set n=2 for your second case and if course n=0 is the base case.

    Alternatively, just start from -n in enumerate, which gives you the right values (but different index):

    In []:
    n = 1
    for index, value in enumerate(range(50), -n):
        if index % 10 == 0:
            print(index,value)
    
    Out[]:
    0 1
    10 11
    20 21
    30 31
    40 41
    

    But you really don't need to enumerate and % the index to get every 10th value, assuming you want to work on any iterable just use itertools.islice(), e.g.

    In []:
    import itertools as it
    n = 0
    for value in it.islice(range(50), n, None, 10):
        print(value)
    
    Out[]:
    0
    10
    20
    30
    40
    

    Then just change the value of n, e.g.:

    In []:
    n = 1
    for value in it.islice(range(50), n, None, 10):
        print(value)
    
    Out[]:
    1
    11
    21
    31
    41