Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
List Comprehensions
#11
Using cProfile shows that the for loop having to call append for each item of the list is what takes up all the time(I think).

import cProfile

ordinary_loop = '''
lst = range(10000000)
l = []
for i in lst:
    l.append(int(i))
'''
list_comp = '''
lst = range(10000000)
[int(i) for i in lst]
'''
_map = '''
lst = range(10000000)
list(map(int, lst))
'''

cProfile.run(ordinary_loop)
cProfile.run(list_comp)
cProfile.run(_map)
Output

         10000003 function calls in 6.797 seconds

   Ordered by: standard name

   ncalls  tottime  percall  cumtime  percall filename:lineno(function)
        1    5.728    5.728    6.797    6.797 <string>:2(<module>)
        1    0.000    0.000    6.797    6.797 {built-in method exec}
 10000000    1.068    0.000    1.068    0.000 {method 'append' of 'list' objects}
        1    0.000    0.000    0.000    0.000 {method 'disable' of '_lsprof.Profiler' objects}


         4 function calls in 3.155 seconds

   Ordered by: standard name

   ncalls  tottime  percall  cumtime  percall filename:lineno(function)
        1    0.220    0.220    3.155    3.155 <string>:2(<module>)
        1    2.935    2.935    2.935    2.935 <string>:3(<listcomp>)
        1    0.000    0.000    3.155    3.155 {built-in method exec}
        1    0.000    0.000    0.000    0.000 {method 'disable' of '_lsprof.Profiler' objects}


         3 function calls in 2.321 seconds

   Ordered by: standard name

   ncalls  tottime  percall  cumtime  percall filename:lineno(function)
        1    2.321    2.321    2.321    2.321 <string>:2(<module>)
        1    0.000    0.000    2.321    2.321 {built-in method exec}
        1    0.000    0.000    0.000    0.000 {method 'disable' of '_lsprof.Profiler' objects}
Reply


Messages In This Thread
List Comprehensions - by ATXpython - Oct-01-2016, 06:07 PM
RE: List Comprehensions - by ichabod801 - Oct-01-2016, 06:30 PM
RE: List Comprehensions - by snippsat - Oct-01-2016, 06:38 PM
RE: List Comprehensions - by Ofnuts - Oct-01-2016, 09:20 PM
RE: List Comprehensions - by Larz60+ - Oct-01-2016, 09:44 PM
RE: List Comprehensions - by Skaperen - Oct-02-2016, 01:02 AM
RE: List Comprehensions - by metulburr - Oct-02-2016, 01:09 AM
RE: List Comprehensions - by snippsat - Oct-02-2016, 08:56 AM
RE: List Comprehensions - by Yoriz - Oct-02-2016, 11:39 AM
RE: List Comprehensions - by Larz60+ - Oct-02-2016, 11:59 AM
RE: List Comprehensions - by Yoriz - Oct-02-2016, 12:16 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  abusing comprehensions for one line loops Skaperen 6 2,623 Dec-16-2019, 11:22 PM
Last Post: Skaperen

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020