3

How to print every 4th item from a list?

list = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm']
Michael Petrotta
  • 59,888
  • 27
  • 145
  • 179

3 Answers3

8

Use a slice:

fourth_items = list[3::4] # ['d', 'h', 'l']
for i in fourth_items: print i
SheetJS
  • 22,470
  • 12
  • 65
  • 75
1

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()
Neo Ko
  • 1,365
  • 15
  • 25
  • 1
    `list` is not a keyword. It is a function, and it's not advisable to use a variable called `list`, but it's not a keyword: http://hg.python.org/cpython/file/2.7/Lib/keyword.py#l16 http://hg.python.org/cpython/file/3.2/Lib/keyword.py#l16 – SheetJS Oct 24 '13 at 02:39
  • @Nirk, I think I use the pop method is not totally wrong,after all the question is print the 4th item, it doesn't limit its printing is in normal order or reverse order. – Neo Ko Oct 24 '13 at 03:11
0

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
Arthur Weborg
  • 8,280
  • 5
  • 30
  • 67