How to print every 4th item from a list?
list = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm']
How to print every 4th item from a list?
list = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm']
Use a slice:
fourth_items = list[3::4] # ['d', 'h', 'l']
for i in fourth_items: print i
Thanks Nirks's comment,I correct my answer. the list is built-in function in python, which is not advice to use as a variable name i change it into list_test.
list_test = list('abcdefghijklm')
tmp = list_test[3::4]
and here is the different part
print in normal order:
for i in tmp: print i
or
print in reverse order :
while tmp: print tmp.pop()
Why not loop through, increment by 4 on every iteration. You can get the length of an array in python with len(list)
index = 0 #or start at 3, pending on where you want to start
while index < len(list) :
print list[index]
index +=4