Why set automatically unpacks range, but list doesn`t? How this can be used?

Viewed 42

I create list and set with range. Set unpacks range, list doesn`t

>>> my_list = [range(5)]
>>> my_set = set(range(5))
>>> my_list
[range(0, 5)]
>>> my_set
{0, 1, 2, 3, 4}
>>> my_list = [*range(5)]
>>> my_list
[0, 1, 2, 3, 4]
3 Answers

The reason why it doesn't unpack is because my_list is only putting two brackets next to it, if you do that with set it will be the same:

>>> my_set = {range(5)}
{range(0, 5)}

But if you do list(...) it will unpack:

>>> my_set = list(range(5))
[0, 1, 2, 3, 4]

It's because you are explicitly creating a new object with range(5) as an argument. This can be done with lists too.

>>> my_list = list(range(5))
>>> my_list
[0, 1, 2, 3, 4]

In this piece of your code:

>>> my_list = [range(5)]

You are creating a list with one generator as its only value. Remember, Python is a first class language, which makes it possible to do this. You can also do this with a set:

>>> my_set = {range(5)}
>>> my_set
{range(0, 5)}

range function returns class

type(range(5))
<class 'range'>

you are building a list of range objects.if you define

foo = {range(5)}

it will be the set of range objects.

You should do the same for both to got the same behavior

foo = list(range(5))
bar = set(range(5))
Related