Skip to content
Advertisement

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

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]

Advertisement

Answer

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]
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement