A
A
Alan Gibizov2020-06-06 12:32:53
Python
Alan Gibizov, 2020-06-06 12:32:53

What is the difference between list() and []?

Until now, I thought that these should be equivalent entries.

print(list(range(5)))
print([range(5)])

But no. Somewhere under the hood it is very different.
[0, 1, 2, 3, 4]
[range(0, 5)]

What is the difference?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
Sergey Gornostaev, 2020-06-06
@phaggi

[]- 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.

A
Alexander, 2020-06-06
@NeiroNx

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 question

Ask a Question

731 491 924 answers to any question