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?
You can slice the list in steps of two; exploiting memory:
for x in ls[::2]:
print(x)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With