15

Is there any "pythonic" way to do this? I am pretty sure my method is not good:

sample = "This is a string"
n = 3 # I want to iterate over every third element
i = 1
for x in sample:
    if i % n == 0:
        # do something with x
    else:
        # do something else with x
    i += 1
1
  • 3
    for i,x in enumerate(sample,1): Commented Jul 1, 2018 at 9:11

4 Answers 4

22

you can use step for example sample[start:stop:step]

If you want to iterate over every second element you can do :

sample = "This is a string"

for x in sample[::2]:
    print(x)

output

T
i

s
a
s
r
n
Sign up to request clarification or add additional context in comments.

2 Comments

it doesn't answer to "do something every even item and do something else every odd item" though.
@Jean-FrançoisFabre Yes but still it is useful and partly answers my question
14

If you want to do something every nth step, and something else for other cases, you could use enumerate to get the index, and use modulus:

sample = "This is a string"
n = 3 # I want to iterate over every third element
for i,x in enumerate(sample):
    if i % n == 0:
        print("do something with x "+x)
    else:
        print("do something else with x "+x)

Note that it doesn't start at 1 but 0. Add an offset to i if you want something else.

To iterate on every nth element only, the best way is to use itertools.islice to avoid creating a "hard" string just to iterate on it:

import itertools
for s in itertools.islice(sample,None,None,n):
    print(s)

result:

T
s
s

r
g

3 Comments

This is the most comprehensive answer
islice is a lot slower than just using a regular slice, since it has to actually retrieve every character from the string and ignore the ones it's not interested in, while a regular slice can skip straight to the elements it needs.
probably a trade-off between creating a string with s[::n] (memory copy but fast iteration). If the string is big, maybe islice is better but you're probably right for regular-sized strings.
1

Logic to print every nth character:

#Sample input = 'abcdefghijkl'
#n = 4
for i in range(0,4):
    for x in input[i::4]:
        print(x, end='')

Output:

aeibfjcgkdhl

Comments

0

Seeing the answers above - except the mostly voted one (which doesn't fully cover the request) - it was mainly division in a loop. Why not keep it more "programmatic", even if yet not that pythonic? Here is example based on original question (no division used):

sample = "This is a string"
n = 3 # I want to iterate over every third element
i = 1
for x in sample:
    if n == i:
        i = 0
        # do something with x
    else:
        # do something else with x
    i += 1

If you sill like to process with valid index:

sample = "This is a string"
n = 3 # I want to iterate over every third element
# (!) here do something else with all elements within list/substring: sample[0:n-1]
for i in range(n-1, len(sample), n):
    # (!) here do something with element: sample[i]
    # (!) here do something else with all elements within list/substring: sample[i+1:i+n]

And now coming back to solution with division, but as a single line:

sample = "This is a string"
n = 3 # I want to iterate over every third element
# you can call below your own correspondent functions (according to case) instead of print() ;-)
_ = [print('Do something: ' + sample[i]) if 0 == ((1+i) % n) else print('Do something else: ' + sample[i]) for i in range(len(sample))]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.