Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Processing alternate element in for loop without using index value [duplicate]

I have list of elements with dictionary, for simplicity I have written them as strings:

ls = ['element1', 'element2', 'element3', 'element4', 'element5', 'element6', 'element7', 'element8', 'element9', 'element10']

I am trying to process pair of element from list as follow:

#m1. Step for loop by size two with if condition 
for x in ls:
    if ls.index(x)%2 == 0:
        # my code to be process
        print(x) # for simplicity I just printed element


#m2. tried another way like below:
for x in range(0, len(ls), 2):
    # this way give me output of alternate element from list
    print(ls[x])

Is there any way to get only alternate elements while iterating the list items in m1 just like m2?

like image 631
Gahan Avatar asked Jun 12 '26 06:06

Gahan


1 Answers

You can slice the list in steps of two; exploiting memory:

for x in ls[::2]:
    print(x)
like image 145
Moses Koledoye Avatar answered Jun 13 '26 19:06

Moses Koledoye



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!