Python Forum
Lists: concatenate vs. extend vs. chain
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Lists: concatenate vs. extend vs. chain
#5
OK, thanks for pointing out my mistake. It can be a string, but I miss the parenthesis
 
#https://twitter.com/raymondh/status/916721150436057089
import timeit
from itertools import chain

 
def using_concatenation():
    one = range(1, 1000000)
    two = range(1, 1000000)
    three = one + two + one + two + one + two
    
    
def using_extend():
    one = range(1, 1000000)
    two = range(1, 1000000)
    three = range(1, 1000000)
    four = range(1, 1000000)
    one.extend(two)
    one.extend(three)
    one.extend(four)
    one.extend(two)
    one.extend(three)
    one.extend(four)

    
def using_chain():
    one = range(1, 1000000)
    two = range(1, 1000000)
    three = chain(one, two, one, two, one, two)
    
 
if __name__ == '__main__':
   repeat = 10
   print('repeat {}'.format(repeat))
   print('using concatenation --> {}'.format(timeit.timeit("using_concatenation()", number=repeat, setup="from __main__ import using_concatenation")))
   print('using extend --> {}'.format(timeit.timeit("using_extend()", number=repeat, setup="from __main__ import using_extend")))
   print('using chain --> {}'.format(timeit.timeit("using_chain()", number=repeat, setup="from __main__ import using_chain")))
win7, python2
Output:
repeat 10 using concatenation --> 2.4562610593 using extend --> 1.63672606549 using chain --> 0.272854924754
will check also python3 at home
Reply


Messages In This Thread
Lists: concatenate vs. extend vs. chain - by buran - Oct-09-2017, 08:44 AM
RE: Lists: concatenate vs. extend vs. chain - by buran - Oct-09-2017, 02:38 PM

Forum Jump:

User Panel Messages

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