1

I have a list of 20 items. I want to create a new list than only contains every 5th item of the list.

Here is was I have:

    listA=[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]
    for i in len(range(listA)):
      print i

How can I create listB from listA using Python? listB should be equal to [5, 10, 15, 20].

Eli Sadoff
  • 7,173
  • 6
  • 33
  • 61
airzinger1
  • 151
  • 9

2 Answers2

6

You can use this idiom

listB = listA[4::5]

This means starting from index 4, pick every 5th element.

Eli Sadoff
  • 7,173
  • 6
  • 33
  • 61
0

Another method is using the range() function to create a list of integers with increments (steps) of 5 between them, then using them to access the indexes of the original list to append them to a new one:

listB=[]
for i in range(4,len(listA),5):
    listB.append(listA[i])

The range(start, stop[, step]) function returns a list of integers, based on the arguments used:

  1. start - the first integer in the list (optional, defaults to 0).
  2. stop - the last integer generated in the list will be the greatest, but less than the value of stop (stop will not be in the list).
  3. step - the increment for values in the list (defaults to 1, can be made negative - to produce decreasing lists).
maze88
  • 850
  • 2
  • 9
  • 15