I am new to python and so I am experimenting a little bit, but I have a little problem now.
I have a list of n numbers and I want to make a new list that contains only every second pair of the numbers.
So basically if I have list like this
oldlist = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
then I want that the new list looks like this
newlist = [3, 4, 7, 8]
I already tried the slice()
function, but I didn’t find any way to make it slice my list into pairs. Then I thought that I could use two slice()
functions that goes by four and are moved by one, but if I merge these two new lists they won’t be in the right order.
Advertisement
Answer
a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] b = [a[i] for i in range(len(a)) if i%4 in (2,3)] # Output: b = [3, 4, 7, 8]
Here, we use the idea that the 3rd,4th,7th,8th..and so on. indices leave either 2 or 3 as the remainder when divided by 4.