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:
start
- the first integer in the list (optional, defaults to0
).stop
- the last integer generated in the list will be the greatest, but less than the value ofstop
(stop
will not be in the list).step
- the increment for values in the list (defaults to1
, can be made negative - to produce decreasing lists).
Post a Comment for "Only Create List In Python With Every 5th Item?"