1

I'm learning python and am studying from the book Dive into the Python. It says :

The built−in range function returns a list of integers. In its simplest form, it takes an upper limit and returns a zero−based list counting up to but not including the upper limit.

According to what it says, it returns a list. I thought that I could append a value to it with append function, but I couldn't.

>>> l = range(7)
>>> l
[0, 1, 2, 3, 4, 5, 6]
>>> l.append(13)
>>> l
[0, 1, 2, 3, 4, 5, 6, 13]
>>> l = range(7).append(13)
>>> l

It doesn't print anything, what's the reason?

yunusaydin
  • 347
  • 2
  • 13
  • 3
    Side note: `range` only returns a list in Python 2.x. In Python 3, you'll get an `AttributeError: 'range' object has no attribute 'append'` – Lev Levitsky Jun 12 '14 at 18:50

1 Answers1

6

The reason is that list.append operates in-place and therefore always returns None.

In other words, this line:

l = range(7).append(13)

is equivalent to this:

l = None

Note too that the example you posted proves that appending values to the list returned by range works as expected if you call list.append on its own line:

>>> l = range(7)
>>> l.append(13)  # Call list.append on its own line
>>> l  # And it works as expected
[0, 1, 2, 3, 4, 5, 6, 13]
>>>