rh1990
rh1990

Reputation: 940

Removing n multiple items from a list

Question

I want to remove items from a list such that I keep the first n items, and remove the next 2n items.

For example

for n=8, I want to keep the first 8, remove the next 16 and repeat this as necessary:

a = range(48)

Which I want to become

[0,1,2,3,4,5,6,7,24,25,26,27,28,29,30,31]

This is to pick out the first 8 hours of a day, and run a function on each hour.

I've found it hard to phrase this in search queries so the answer is probably simple but I've had no luck!

Upvotes: 2

Views: 69

Answers (3)

Serge Ballesta
Serge Ballesta

Reputation: 148890

You could just use a comprehension list:

[ a[i] for i in range(len(a)) if (i % 24 < 8) ]

The above only create a new list. If you want to edit the list in place, you must explicitely delete unwanted elements, starting from the end to avoid changing indexes:

for i in range(len(a) - 1, 0, -1):
    if i % 24 >= 8:
        del a[i]

Upvotes: 1

Extalia
Extalia

Reputation: 23

     def hours(n):
             items = [x for x in range(49)]
             del items[n:n*3]
     print(items)

hours(8)

Depending on how new you are you might have a hard time understanding this code, so I will try to explain a little:

We start by creating a function which takes a parameter n which, for test purposes, we will be using 8 then we use a list comprehension to generate all our numbers (0, 48) and then delete the unneeded elements using the del statement, we are deleting from the nth to the n*3 element in the list. For example, if n were to be passed as 9 our use of the del statement could be translated as: del [9:27].

Hope this makes sense.

Upvotes: 1

Ahasanul Haque
Ahasanul Haque

Reputation: 11134

This should be quite easy to understand

a = range(48)
n=8
result=[]
while a:
    result+= a[:n]
    a=a[n*3:]

print result 

Upvotes: 0

Related Questions