Reputation: 1313
In certain styles of python, everything is a generator, e.g. uses yield
rather than constructing and return
ing a list. If you need to use it as a list, you can just call list(gen)
.
If I have a list already, what is the cost of calling list(my_list)
?
Use: I have a variable that I know has an iterator and might be a list, but I need to use it as a list. Is it better/more pythonic to do my_list = list(my_list)
or some other way of checking its list-ness?
If it matters I'm using Python 3.5.
Upvotes: 4
Views: 173
Reputation: 59114
If you call list(x)
you are certainly creating a new list, even if x
is already a list. If you want to avoid it, you can use isinstance(x, list)
to check if x
is a list or not.
if not isinstance(x, list):
x = list(x)
Upvotes: 5