1

I need a loop containing range(3,666,2) and 2 (for the sieve of Eratosthenes, by the way). This doesn't work ("AttributeError: 'range' object has no attribute 'extend'" ... or "append"):

primes = range(3,limit,2)
primes.extend(2)

How can I do it in the simple intuitive pythonesque way?

2
  • Please print out your expected o/p. Commented Jan 16, 2014 at 12:18
  • @python-coder: Python 3: AttributeError: 'range' object has no attribute 'extend'. Commented Jan 16, 2014 at 12:27

2 Answers 2

8

range() in Python 3 returns a dedicated immutable sequence object. You'll have to turn it into a list to extend it:

primes = list(range(3, limit, 2))
primes.append(2)

Note that I used list.append(), not list.extend() (which expects a sequence of values, not one integer).

However, you probably want to start your loop with 2, not end it. Moreover, materializing the whole range into a list requires some memory and kills the efficiency of the object. Use iterator chaining instead:

from itertools import chain

primes = chain([2], range(3, limit, 2))

Now you can loop over primes without materializing a whole list in memory, and still include 2 at the start of the loop.

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

6 Comments

And if I have range(3,ThisIsSuchABigNumber,2) ? Will I do a list of billions just for a range?
@Liviu: exactly, which is why you would not want to do that, really.
@Liviu chain and range are lazy functions. chain will lazily loop over its arguments. So, the entire list will not be created in memory, when invoked. range will return a range object, not the entire list.
When I asked the question, the chain solution wasn't added yet. Now it's hard to choose an answer.
@Liviu: That's up to you. :-) I was trying to first address why .extend() doesn't work on a range() object (assuming you tried to use list methods on it), before showing how it should be done instead. Jon focused on the latter first. Such is the nature of Stack Overflow sometimes, if the answer is reasonably obvious for the regulars, it comes down to the faster typer.
|
5

If you're only looping and don't want to materialise, then:

from itertools import chain
primes = chain([2], range(3, limit, 2))

I think the two makes more sense at the start though...

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.