Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Increase all of a lists values by an increment [duplicate]

Tags:

python

I think I'm having a idiot moment,

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......]
like image 425
i love crysis Avatar asked Jun 09 '13 01:06

i love crysis


2 Answers

Specific answer

With list comprehensions:

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]

Turns out that the 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 bench-marking

After @mgilson posted the comment about numpy, I wondered how it stacked up. I found that for lists shorter than 50 or so elements, list comprehensions are faster, but numpy is faster beyond that.

benchmarks

like image 60
Matthew Adams Avatar answered Nov 02 '22 04:11

Matthew Adams


incremented_list = [x+170 for x in original_list]
like image 4
Amber Avatar answered Nov 02 '22 04:11

Amber