Increase all list values ​​with increment

I think I have an idiot

I have a list and I need to add 170 to each number

list1[1,2,3,4,5,6,7,8......] list2[171,172,173......] 
+4
source share
2 answers

Specific answer

With a list:

 In [2]: list1 = [1,2,3,4,5,6] In [3]: [x+170 for x in list1] Out[3]: [171, 172, 173, 174, 175, 176] 

With map :

 In [5]: map(lambda x: x+170, list1) Out[5]: [171, 172, 173, 174, 175, 176] 

It turns out that list comprehension is twice as fast:

 $ python -m timeit 'list1=[1,2,3,4,5,6]' '[x+170 for x in list1]' 1000000 loops, best of 3: 0.793 usec per loop $ python -m timeit 'list1=[1,2,3,4,5,6]' 'map(lambda x: x+170, list1)' 1000000 loops, best of 3: 1.74 usec per loop 

Some tags for marking

After @mgilson posted a comment about numpy, I wondered how it stacks up. I found that for lists containing less than 50 items, list scans are faster, but the number is less than possible.

benchmarks

+13
source
 incremented_list = [x+170 for x in original_list] 
+1
source

Source: https://habr.com/ru/post/1485241/


All Articles