Skip to content Skip to sidebar Skip to footer

Only Create List In Python With Every 5th Item?

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

Solution 1:

You can use this idiom

listB = listA[4::5]

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

Solution 2:

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).

Post a Comment for "Only Create List In Python With Every 5th Item?"