In Python 3, what is the most efficient way to change the values in a list? -


i'm learning python, , trying change list in different ways. instance, if have list called names this:

names = ["david", "jake", "alex"] 

and want add name "carter" list, efficient way accomplish this? here's of things can do:

names.append("carter")  names = names + ["carter"]  names += ["carter"] 

append fastest. here how build small profile using timeit module

import timeit = (timeit.timeit("l.append('cheese')", setup="l=['meat', 'milk']")) b = (timeit.timeit("l+=['cheese']", setup="l=['meat', 'milk']")) c = (timeit.timeit("append('cheese')", setup="l=['meat', 'milk'];append = l.append")) print ('a', a) print ('b', b) print ('c', c) print ("==> " , (c < < b)) 

as can see, in python access method append takes half of time l.append itself...

a 0.08502503100316972

b 0.1582659209962003

c 0.041991976962890476

==> true


Comments

Popular posts from this blog

authentication - Mongodb revoke acccess to connect test database -

r - Update two sets of radiobuttons reactively - shiny -

ios - Realm over CoreData should I use NSFetchedResultController or a Dictionary? -