Difference between "list(range(1, 10))" and "range(1, 10)"?

Asked

Viewed 190 times

6

I asked that question here How to format all elements of a list in Python?.

In one of the answers, @Ciganomorrisonmendez, put the following excerpt:

list(range(1, 10))

But every time I used the Python, I used to

range(1, 10)

This is a conversion to list? But the range no longer returns a list?

Updating

I ran a test on the command line and the result that was returned was this:

type(range(1, 10))
<type 'list'>

1 answer

5


Not.

range is a class which can be initialized with three arguments: start, end and increment. Therefore, it does not equal a list.

It can generate a list if converted to list because it has the ability to be iterated.

In Python 2, the behavior was different. range effectively generated a list. In Python 3, the object looks more like a generator.

  • Take a look at the update. The terminal is saying that it is a list!

  • It is written that range is currently a type of immutable sequence. This "currently" means "has been modified in recent versions"?

  • Yes, I’ll improve the answer.

  • 1

    Just to top it off - some tools that update code to work simultaneously with Python 2 and Python 3 change the occurrences of range in Python 2 to list(range(...)) - so that the behaviour is identical in both versions.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.