0

I have an array named 'a' with the numbers 1 to 10,000 in it. I would like jump through the list in 2s, which I have managed successfully. However, I want the program to remove every second number, like the number '2' for example, which would be assigned to 'x'. I have tried functions such as .pop() but I don't seem to be getting anywhere. Please can someone help. Am i just using the function wrong?

for x in range(0,9999,2):
    a.pop()

2 Answers 2

2

Why not just create a list of the values you do want. It is a lot more efficient:

a = range(1,10000)

a = a[1::2]     #will contain all the even numbers

By the way, the reason your code is not working is because you are (in a sense) modifying your list while iterating through it. You should avoid it thoroughly unless you are absolutely sure that that is what you want.

The syntax above uses the list[start:end:step] syntax. Therefore, [1::2] will get every second element of the list starting at the second element. Similarly, [::2] will get every second element of the list starting at the default 1st element since no start index was specified.

Sign up to request clarification or add additional context in comments.

5 Comments

Im new to python could you explain what the '::' means?
he is not really modifying his list while iterating over it :)
@GeorgeGeorgeCarmichael, Answer updated. Hope it helps
range(1, 10000, 2) will create a list with odd numbers.
He is not even "in a sense" modifying a list while iterating through it. He is not understanding what .pop() does.
0

Using list comprehension

a = [i for i in range(10000) if not i%2]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.