Skip to content Skip to sidebar Skip to footer

Modify A Large List Without Any Loops In Python

My list is: a=[1,2,3,4] Now I want my list to be: a=[-1,-2,-3,-4] How can I change my list this way without using any loops? Update: this may be a large list, on the order of 100

Solution 1:

Use Python's map functionality

a[:] = map(lambda x: -x, a)

Here's the description of the map function from the above link:

map(function, iterable, ...) Apply function to every item of iterable and return a list of the results. If additional iterable arguments are passed, function must take that many arguments and is applied to the items from all iterables in parallel. If one iterable is shorter than another it is assumed to be extended with None items. If function is None, the identity function is assumed; if there are multiple arguments, map() returns a list consisting of tuples containing the corresponding items from all iterables (a kind of transpose operation). The iterable arguments may be a sequence or any iterable object; the result is always a list.

Solution 2:

some quick and dirty benchmarks from ipython

In [1]: a=range(10000)

In [2]: import numpy 

In [3]: timeit [-i for i in a]
1000 loops, best of 3: 576 us per loop

In [4]: timeit map(lambda i:-i, a)
1000 loops, best of 3: 1.68 ms per loop

In [5]: timeit list(-1*numpy.array(a))
100 loops, best of 3: 2.53 ms per loop

Note that if a can be a numpy array you don't need to wast time on the conversion

In [6]: a = numpy.array(a)

In [7]: timeit -- -a
100000 loops, best of 3: 15.4 us per loop

Solution 3:

You can use the numpy library:

list(-1*numpy.array(a))

Solution 4:

importoperator
a = map(operator.neg, a)

Solution 5:

Well it depends on what you mean by without any loops. In case you just want to avoid explicit loops like

a = [ -x for x in a ]

you could use the map function, that would loop for you.

a = map( lambda x:-x, a)

Post a Comment for "Modify A Large List Without Any Loops In Python"