Understanding python tuple to list performance optimizationHow do I check if a list is empty?Calling an external command in PythonWhat are metaclasses in Python?Finding the index of an item given a list containing it in PythonWhat is the difference between Python's list methods append and extend?Does Python have a ternary conditional operator?Understanding slice notationUnderstanding Python super() with __init__() methodsHow to make a flat list out of list of listsHow do I concatenate two lists in Python?
Why are there not any MRI machines available in Interstellar?
How important is a good quality camera for good photography?
Grid/table with lots of buttons
How can I tell if there was a power cut while I was out?
What is the difference between 1/3, 1/2, and full casters?
How were the LM astronauts supported during the moon landing and ascent? What were the max G's on them during these phases?
Memory capability and powers of 2
"I you already know": is this proper English?
Explanation for a joke about a three-legged dog that walks into a bar
What should I say when a company asks you why someone (a friend) who was fired left?
Why did Saturn V not head straight to the moon?
Area of parallelogram = Area of square. Shear transform
Strange Cron Job takes up 100% of CPU Ubuntu 18 LTS Server
What is a reasonable time for modern human society to adapt to dungeons?
Where is this photo of a group of hikers taken? Is it really in the Ural?
Why is the return type for ftell not fpos_t?
Are glider winch launches rarer in the USA than in the rest of the world? Why?
How do I run a game when my PCs have different approaches to combat?
What to do when you reach a conclusion and find out later on that someone else already did?
Film where a boy turns into a princess
Is it normal practice to screen share with a client?
Are gangsters hired to attack people at a train station classified as a terrorist attack?
How can I prevent corporations from growing their own workforce?
Why did computer video outputs go from digital to analog, then back to digital?
Understanding python tuple to list performance optimization
How do I check if a list is empty?Calling an external command in PythonWhat are metaclasses in Python?Finding the index of an item given a list containing it in PythonWhat is the difference between Python's list methods append and extend?Does Python have a ternary conditional operator?Understanding slice notationUnderstanding Python super() with __init__() methodsHow to make a flat list out of list of listsHow do I concatenate two lists in Python?
.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;
I have a tuple, say, atup = (1,3,4,5,6,6,7,78,8) and produced dynamically by list of tuples when iterated (generator yield). Each tuple needs to get converted to list so each elements of tuple can be transformed further and used in a method. While doing this, I was surprised to learn that just doing list(atup) is much faster than using list comprehension like this [i for i in atup]. Here is what I did:
Performance Test 1:
timeit.timeit('list((1,3,4,5,6,6,7,78,8))', number=100000)
0.02268475245609025
Performance Test 2:
timeit.timeit('[i for i in (1,3,4,5,6,6,7,78,8)]', number=100000)
0.05304025196801376
Can you please explain this ?
python list tuples
add a comment |
I have a tuple, say, atup = (1,3,4,5,6,6,7,78,8) and produced dynamically by list of tuples when iterated (generator yield). Each tuple needs to get converted to list so each elements of tuple can be transformed further and used in a method. While doing this, I was surprised to learn that just doing list(atup) is much faster than using list comprehension like this [i for i in atup]. Here is what I did:
Performance Test 1:
timeit.timeit('list((1,3,4,5,6,6,7,78,8))', number=100000)
0.02268475245609025
Performance Test 2:
timeit.timeit('[i for i in (1,3,4,5,6,6,7,78,8)]', number=100000)
0.05304025196801376
Can you please explain this ?
python list tuples
add a comment |
I have a tuple, say, atup = (1,3,4,5,6,6,7,78,8) and produced dynamically by list of tuples when iterated (generator yield). Each tuple needs to get converted to list so each elements of tuple can be transformed further and used in a method. While doing this, I was surprised to learn that just doing list(atup) is much faster than using list comprehension like this [i for i in atup]. Here is what I did:
Performance Test 1:
timeit.timeit('list((1,3,4,5,6,6,7,78,8))', number=100000)
0.02268475245609025
Performance Test 2:
timeit.timeit('[i for i in (1,3,4,5,6,6,7,78,8)]', number=100000)
0.05304025196801376
Can you please explain this ?
python list tuples
I have a tuple, say, atup = (1,3,4,5,6,6,7,78,8) and produced dynamically by list of tuples when iterated (generator yield). Each tuple needs to get converted to list so each elements of tuple can be transformed further and used in a method. While doing this, I was surprised to learn that just doing list(atup) is much faster than using list comprehension like this [i for i in atup]. Here is what I did:
Performance Test 1:
timeit.timeit('list((1,3,4,5,6,6,7,78,8))', number=100000)
0.02268475245609025
Performance Test 2:
timeit.timeit('[i for i in (1,3,4,5,6,6,7,78,8)]', number=100000)
0.05304025196801376
Can you please explain this ?
python list tuples
python list tuples
asked Mar 26 at 16:00
NullExceptionNullException
1,5846 gold badges18 silver badges34 bronze badges
1,5846 gold badges18 silver badges34 bronze badges
add a comment |
add a comment |
2 Answers
2
active
oldest
votes
The list comprehension has to iterate over the tuple at the Python level:
>>> dis.dis("[i for i in (1,2,3)]")
1 0 LOAD_CONST 0 (<code object <listcomp> at 0x1075c0c90, file "<dis>", line 1>)
2 LOAD_CONST 1 ('<listcomp>')
4 MAKE_FUNCTION 0
6 LOAD_CONST 5 ((1, 2, 3))
8 GET_ITER
10 CALL_FUNCTION 1
12 RETURN_VALUE
list
iterates over the tuple itself, and uses the C API to do it without going through (as much of) the Python data model.
>>> dis.dis("list((1,2,3))")
1 0 LOAD_NAME 0 (list)
2 LOAD_CONST 3 ((1, 2, 3))
4 CALL_FUNCTION 1
6 RETURN_VALUE
The Python-level iteration is more clearly seen in Python 2, which implements list comprehensions in a different fashion.
>>> def f():
... return [i for i in (1,2,3)]
...
>>> dis.dis(f)
2 0 BUILD_LIST 0
3 LOAD_CONST 4 ((1, 2, 3))
6 GET_ITER
>> 7 FOR_ITER 12 (to 22)
10 STORE_FAST 0 (i)
13 LOAD_FAST 0 (i)
16 LIST_APPEND 2
19 JUMP_ABSOLUTE 7
>> 22 RETURN_VALUE
As @blhsing points out, you can get disassemble the code object generated by the list comprehension in Python 3 to see the same thing.
>>> code = compile('[i for i in (1,2,3)]', '', 'eval')
>>> dis(code.co_consts[0])
1 0 BUILD_LIST 0
2 LOAD_FAST 0 (.0)
>> 4 FOR_ITER 8 (to 14)
6 STORE_FAST 1 (i)
8 LOAD_FAST 1 (i)
10 LIST_APPEND 2
12 JUMP_ABSOLUTE 4
>> 14 RETURN_VALUE
1
Note that in Python 3 one would simply have to disassemble the code object stored in theco_consts
list attribute of the parent code object as indexed to see the content of its byte codes. For example: repl.it/repls/SomberUniformAngles
– blhsing
Mar 26 at 16:20
1
@blhsing Oh, thanks. It hadn't occurred to me to try to disassemble the code object.
– chepner
Mar 26 at 16:35
1
In python 3.7 I've noticeddis
recurses into any nested code objects automatically, and accepts a depth parameter!
– juanpa.arrivillaga
Mar 26 at 17:37
Oh! So it does.
– chepner
Mar 26 at 17:38
add a comment |
The list
constructor is implemented purely in C and has therefore minimal overhead, while with a list comprehension the Python compiler has to build a temporary function, build an iterator, store the iterator's output as variable i
, and load the variable i
to append to a list, which are a lot more Python byte codes to execute than simply loading a tuple and calling the list
constructor.
add a comment |
Your Answer
StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");
StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "1"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);
else
createEditor();
);
function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);
);
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55361457%2funderstanding-python-tuple-to-list-performance-optimization%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
2 Answers
2
active
oldest
votes
2 Answers
2
active
oldest
votes
active
oldest
votes
active
oldest
votes
The list comprehension has to iterate over the tuple at the Python level:
>>> dis.dis("[i for i in (1,2,3)]")
1 0 LOAD_CONST 0 (<code object <listcomp> at 0x1075c0c90, file "<dis>", line 1>)
2 LOAD_CONST 1 ('<listcomp>')
4 MAKE_FUNCTION 0
6 LOAD_CONST 5 ((1, 2, 3))
8 GET_ITER
10 CALL_FUNCTION 1
12 RETURN_VALUE
list
iterates over the tuple itself, and uses the C API to do it without going through (as much of) the Python data model.
>>> dis.dis("list((1,2,3))")
1 0 LOAD_NAME 0 (list)
2 LOAD_CONST 3 ((1, 2, 3))
4 CALL_FUNCTION 1
6 RETURN_VALUE
The Python-level iteration is more clearly seen in Python 2, which implements list comprehensions in a different fashion.
>>> def f():
... return [i for i in (1,2,3)]
...
>>> dis.dis(f)
2 0 BUILD_LIST 0
3 LOAD_CONST 4 ((1, 2, 3))
6 GET_ITER
>> 7 FOR_ITER 12 (to 22)
10 STORE_FAST 0 (i)
13 LOAD_FAST 0 (i)
16 LIST_APPEND 2
19 JUMP_ABSOLUTE 7
>> 22 RETURN_VALUE
As @blhsing points out, you can get disassemble the code object generated by the list comprehension in Python 3 to see the same thing.
>>> code = compile('[i for i in (1,2,3)]', '', 'eval')
>>> dis(code.co_consts[0])
1 0 BUILD_LIST 0
2 LOAD_FAST 0 (.0)
>> 4 FOR_ITER 8 (to 14)
6 STORE_FAST 1 (i)
8 LOAD_FAST 1 (i)
10 LIST_APPEND 2
12 JUMP_ABSOLUTE 4
>> 14 RETURN_VALUE
1
Note that in Python 3 one would simply have to disassemble the code object stored in theco_consts
list attribute of the parent code object as indexed to see the content of its byte codes. For example: repl.it/repls/SomberUniformAngles
– blhsing
Mar 26 at 16:20
1
@blhsing Oh, thanks. It hadn't occurred to me to try to disassemble the code object.
– chepner
Mar 26 at 16:35
1
In python 3.7 I've noticeddis
recurses into any nested code objects automatically, and accepts a depth parameter!
– juanpa.arrivillaga
Mar 26 at 17:37
Oh! So it does.
– chepner
Mar 26 at 17:38
add a comment |
The list comprehension has to iterate over the tuple at the Python level:
>>> dis.dis("[i for i in (1,2,3)]")
1 0 LOAD_CONST 0 (<code object <listcomp> at 0x1075c0c90, file "<dis>", line 1>)
2 LOAD_CONST 1 ('<listcomp>')
4 MAKE_FUNCTION 0
6 LOAD_CONST 5 ((1, 2, 3))
8 GET_ITER
10 CALL_FUNCTION 1
12 RETURN_VALUE
list
iterates over the tuple itself, and uses the C API to do it without going through (as much of) the Python data model.
>>> dis.dis("list((1,2,3))")
1 0 LOAD_NAME 0 (list)
2 LOAD_CONST 3 ((1, 2, 3))
4 CALL_FUNCTION 1
6 RETURN_VALUE
The Python-level iteration is more clearly seen in Python 2, which implements list comprehensions in a different fashion.
>>> def f():
... return [i for i in (1,2,3)]
...
>>> dis.dis(f)
2 0 BUILD_LIST 0
3 LOAD_CONST 4 ((1, 2, 3))
6 GET_ITER
>> 7 FOR_ITER 12 (to 22)
10 STORE_FAST 0 (i)
13 LOAD_FAST 0 (i)
16 LIST_APPEND 2
19 JUMP_ABSOLUTE 7
>> 22 RETURN_VALUE
As @blhsing points out, you can get disassemble the code object generated by the list comprehension in Python 3 to see the same thing.
>>> code = compile('[i for i in (1,2,3)]', '', 'eval')
>>> dis(code.co_consts[0])
1 0 BUILD_LIST 0
2 LOAD_FAST 0 (.0)
>> 4 FOR_ITER 8 (to 14)
6 STORE_FAST 1 (i)
8 LOAD_FAST 1 (i)
10 LIST_APPEND 2
12 JUMP_ABSOLUTE 4
>> 14 RETURN_VALUE
1
Note that in Python 3 one would simply have to disassemble the code object stored in theco_consts
list attribute of the parent code object as indexed to see the content of its byte codes. For example: repl.it/repls/SomberUniformAngles
– blhsing
Mar 26 at 16:20
1
@blhsing Oh, thanks. It hadn't occurred to me to try to disassemble the code object.
– chepner
Mar 26 at 16:35
1
In python 3.7 I've noticeddis
recurses into any nested code objects automatically, and accepts a depth parameter!
– juanpa.arrivillaga
Mar 26 at 17:37
Oh! So it does.
– chepner
Mar 26 at 17:38
add a comment |
The list comprehension has to iterate over the tuple at the Python level:
>>> dis.dis("[i for i in (1,2,3)]")
1 0 LOAD_CONST 0 (<code object <listcomp> at 0x1075c0c90, file "<dis>", line 1>)
2 LOAD_CONST 1 ('<listcomp>')
4 MAKE_FUNCTION 0
6 LOAD_CONST 5 ((1, 2, 3))
8 GET_ITER
10 CALL_FUNCTION 1
12 RETURN_VALUE
list
iterates over the tuple itself, and uses the C API to do it without going through (as much of) the Python data model.
>>> dis.dis("list((1,2,3))")
1 0 LOAD_NAME 0 (list)
2 LOAD_CONST 3 ((1, 2, 3))
4 CALL_FUNCTION 1
6 RETURN_VALUE
The Python-level iteration is more clearly seen in Python 2, which implements list comprehensions in a different fashion.
>>> def f():
... return [i for i in (1,2,3)]
...
>>> dis.dis(f)
2 0 BUILD_LIST 0
3 LOAD_CONST 4 ((1, 2, 3))
6 GET_ITER
>> 7 FOR_ITER 12 (to 22)
10 STORE_FAST 0 (i)
13 LOAD_FAST 0 (i)
16 LIST_APPEND 2
19 JUMP_ABSOLUTE 7
>> 22 RETURN_VALUE
As @blhsing points out, you can get disassemble the code object generated by the list comprehension in Python 3 to see the same thing.
>>> code = compile('[i for i in (1,2,3)]', '', 'eval')
>>> dis(code.co_consts[0])
1 0 BUILD_LIST 0
2 LOAD_FAST 0 (.0)
>> 4 FOR_ITER 8 (to 14)
6 STORE_FAST 1 (i)
8 LOAD_FAST 1 (i)
10 LIST_APPEND 2
12 JUMP_ABSOLUTE 4
>> 14 RETURN_VALUE
The list comprehension has to iterate over the tuple at the Python level:
>>> dis.dis("[i for i in (1,2,3)]")
1 0 LOAD_CONST 0 (<code object <listcomp> at 0x1075c0c90, file "<dis>", line 1>)
2 LOAD_CONST 1 ('<listcomp>')
4 MAKE_FUNCTION 0
6 LOAD_CONST 5 ((1, 2, 3))
8 GET_ITER
10 CALL_FUNCTION 1
12 RETURN_VALUE
list
iterates over the tuple itself, and uses the C API to do it without going through (as much of) the Python data model.
>>> dis.dis("list((1,2,3))")
1 0 LOAD_NAME 0 (list)
2 LOAD_CONST 3 ((1, 2, 3))
4 CALL_FUNCTION 1
6 RETURN_VALUE
The Python-level iteration is more clearly seen in Python 2, which implements list comprehensions in a different fashion.
>>> def f():
... return [i for i in (1,2,3)]
...
>>> dis.dis(f)
2 0 BUILD_LIST 0
3 LOAD_CONST 4 ((1, 2, 3))
6 GET_ITER
>> 7 FOR_ITER 12 (to 22)
10 STORE_FAST 0 (i)
13 LOAD_FAST 0 (i)
16 LIST_APPEND 2
19 JUMP_ABSOLUTE 7
>> 22 RETURN_VALUE
As @blhsing points out, you can get disassemble the code object generated by the list comprehension in Python 3 to see the same thing.
>>> code = compile('[i for i in (1,2,3)]', '', 'eval')
>>> dis(code.co_consts[0])
1 0 BUILD_LIST 0
2 LOAD_FAST 0 (.0)
>> 4 FOR_ITER 8 (to 14)
6 STORE_FAST 1 (i)
8 LOAD_FAST 1 (i)
10 LIST_APPEND 2
12 JUMP_ABSOLUTE 4
>> 14 RETURN_VALUE
edited Mar 26 at 16:34
answered Mar 26 at 16:12
chepnerchepner
279k40 gold badges274 silver badges370 bronze badges
279k40 gold badges274 silver badges370 bronze badges
1
Note that in Python 3 one would simply have to disassemble the code object stored in theco_consts
list attribute of the parent code object as indexed to see the content of its byte codes. For example: repl.it/repls/SomberUniformAngles
– blhsing
Mar 26 at 16:20
1
@blhsing Oh, thanks. It hadn't occurred to me to try to disassemble the code object.
– chepner
Mar 26 at 16:35
1
In python 3.7 I've noticeddis
recurses into any nested code objects automatically, and accepts a depth parameter!
– juanpa.arrivillaga
Mar 26 at 17:37
Oh! So it does.
– chepner
Mar 26 at 17:38
add a comment |
1
Note that in Python 3 one would simply have to disassemble the code object stored in theco_consts
list attribute of the parent code object as indexed to see the content of its byte codes. For example: repl.it/repls/SomberUniformAngles
– blhsing
Mar 26 at 16:20
1
@blhsing Oh, thanks. It hadn't occurred to me to try to disassemble the code object.
– chepner
Mar 26 at 16:35
1
In python 3.7 I've noticeddis
recurses into any nested code objects automatically, and accepts a depth parameter!
– juanpa.arrivillaga
Mar 26 at 17:37
Oh! So it does.
– chepner
Mar 26 at 17:38
1
1
Note that in Python 3 one would simply have to disassemble the code object stored in the
co_consts
list attribute of the parent code object as indexed to see the content of its byte codes. For example: repl.it/repls/SomberUniformAngles– blhsing
Mar 26 at 16:20
Note that in Python 3 one would simply have to disassemble the code object stored in the
co_consts
list attribute of the parent code object as indexed to see the content of its byte codes. For example: repl.it/repls/SomberUniformAngles– blhsing
Mar 26 at 16:20
1
1
@blhsing Oh, thanks. It hadn't occurred to me to try to disassemble the code object.
– chepner
Mar 26 at 16:35
@blhsing Oh, thanks. It hadn't occurred to me to try to disassemble the code object.
– chepner
Mar 26 at 16:35
1
1
In python 3.7 I've noticed
dis
recurses into any nested code objects automatically, and accepts a depth parameter!– juanpa.arrivillaga
Mar 26 at 17:37
In python 3.7 I've noticed
dis
recurses into any nested code objects automatically, and accepts a depth parameter!– juanpa.arrivillaga
Mar 26 at 17:37
Oh! So it does.
– chepner
Mar 26 at 17:38
Oh! So it does.
– chepner
Mar 26 at 17:38
add a comment |
The list
constructor is implemented purely in C and has therefore minimal overhead, while with a list comprehension the Python compiler has to build a temporary function, build an iterator, store the iterator's output as variable i
, and load the variable i
to append to a list, which are a lot more Python byte codes to execute than simply loading a tuple and calling the list
constructor.
add a comment |
The list
constructor is implemented purely in C and has therefore minimal overhead, while with a list comprehension the Python compiler has to build a temporary function, build an iterator, store the iterator's output as variable i
, and load the variable i
to append to a list, which are a lot more Python byte codes to execute than simply loading a tuple and calling the list
constructor.
add a comment |
The list
constructor is implemented purely in C and has therefore minimal overhead, while with a list comprehension the Python compiler has to build a temporary function, build an iterator, store the iterator's output as variable i
, and load the variable i
to append to a list, which are a lot more Python byte codes to execute than simply loading a tuple and calling the list
constructor.
The list
constructor is implemented purely in C and has therefore minimal overhead, while with a list comprehension the Python compiler has to build a temporary function, build an iterator, store the iterator's output as variable i
, and load the variable i
to append to a list, which are a lot more Python byte codes to execute than simply loading a tuple and calling the list
constructor.
answered Mar 26 at 16:12
blhsingblhsing
47.8k5 gold badges17 silver badges47 bronze badges
47.8k5 gold badges17 silver badges47 bronze badges
add a comment |
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55361457%2funderstanding-python-tuple-to-list-performance-optimization%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown