Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the difference between list() and [] [duplicate]

Tags:

python

What's the difference between the following code:

foo = list() 

And

foo = [] 

Python suggests that there is one way of doing things but at times there seems to be more than one.

like image 430
lang2 Avatar asked Nov 15 '15 04:11

lang2


People also ask

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

list is a global name that may be overridden during runtime. list() calls that name. [] is always a list literal.

Is list () and [] the same in Python?

Technically speaking, one is a function that returns an object casted to a list, and the other is the literal list object itself. Kinda like int(0) vs 0 . In practical terms there's no difference. I'd expect [] to be faster, because it does not involve a global lookup followed by a function call.

What is the difference between [] and () in Python?

() is a tuple: An immutable collection of values, usually (but not necessarily) of different types. [] is a list: A mutable collection of values, usually (but not necessarily) of the same type.

What is the difference between list2 list1 and list2 list1 copy ()?

copy() will copy list1 into list2 . That's fine and everything, but it's longer to type than the second way and it just doesn't feel as clean. list2 = list1[:] will put all of the contents of list1 into list2 . This is less typing and most Python programmer's preferred way of copying a list.


2 Answers

For the sake of completion, another thing to note is that list((a,b,c)) will return [a,b,c], whereas [(a,b,c)] will not unpack the tuple. This can be useful when you want to convert a tuple to a list. The reverse works too, tuple([a,b,c]) returns (a,b,c).

Edit: As orlp mentions, this works for any iterable, not just tuples.

like image 36
Andrew Sun Avatar answered Sep 24 '22 23:09

Andrew Sun


One's a function call, and one's a literal:

>>> import dis >>> def f1(): return list() ...  >>> def f2(): return [] ...  >>> dis.dis(f1)   1           0 LOAD_GLOBAL              0 (list)               3 CALL_FUNCTION            0               6 RETURN_VALUE         >>> dis.dis(f2)   1           0 BUILD_LIST               0               3 RETURN_VALUE         

Use the second form. It's more Pythonic, and it's probably faster (since it doesn't involve loading and calling a separate funciton).

like image 59
tckmn Avatar answered Sep 21 '22 23:09

tckmn