Answer the question
In order to leave comments, you need to log in
What is the difference between list() and []?
Until now, I thought that these should be equivalent entries.
print(list(range(5)))
print([range(5)])
[0, 1, 2, 3, 4]
[range(0, 5)]
Answer the question
In order to leave comments, you need to log in
[]
- is a literal for list()
list()
- is a list constructor.
In your case, the difference is in the context. The expression [range(5)]
means "a list containing one generator" and list(range(5))
means "cast the generator to a list". In the second case, the generator is calculated into five integers and a list is constructed from them.
in that range is an iterator and leaf is a list. An iterator returns a value when asked, and a list is a store of all values. List function - polls from the iterator all the values that it can return.
the difference is that either you remember what you have (beginning, end, step, current position) or you remember (10,20,30,40,50,60,...100500) - in the case of a list, it will have to occupy memory with all values, and in the case of an iterator, only store parameters for retrieving a new value.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question