Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

list() vs iterable unpacking in Python 3.5+

Is there any practical difference between list(iterable) and [*iterable] in versions of Python that support the latter?

like image 315
Roman Odaisky Avatar asked Sep 27 '18 14:09

Roman Odaisky


1 Answers

list(x) is a function, [*x] is an expression. You can reassign list, and make it do something else (but you shouldn't).

Talking about cPython, b = list(a) translates to this sequence of bytecodes:

LOAD_NAME                1 (list)
LOAD_NAME                0 (a)
CALL_FUNCTION            1
STORE_NAME               2 (b)

Instead, c = [*a] becomes:

LOAD_NAME                0 (a)
BUILD_LIST_UNPACK        1
STORE_NAME               3 (c)

so you can argue that [*a] might be slightly more efficient, but marginally so.

like image 160
Stefano Sanfilippo Avatar answered Sep 27 '22 22:09

Stefano Sanfilippo