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 10000 elements.
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 10000 elements.
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.
a with a new list with the answers negated. (Of course this might be acceptable to the OP, but it is a subtle difference.)a = ... you do a[:] = ..., then this will change the list in place, by doing a slice assignment. Then other references to this list will see the negated values.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
You can use the numpy library:
list(-1*numpy.array(a))
import operator
a = map(operator.neg, a)
map this answer is probably faster than an explicit loop. The other map answers all use a lambda which will make them slower.Without knowing the exact reason why loop is not required and knowing that there is no other efficient way to negate a list here is my super fast solution (I have no knowledge of the context so this may not work)
class nlist(object):
def __init__(self, l):
self._list = l
def __getitem__(self, key):
return -self._list[key]
def __iter__(self):
for i in self._list:
yield -i
nl = nlist([1,2,3,4])
for i in nl:
print i