Try a list comprehension:
Copyl = [x * 2 for x in l]
This goes through l, multiplying each element by two.
Of course, there's more than one way to do it. If you're into lambda functions and map, you can even do
Copyl = map(lambda x: x * 2, l)
to apply the function lambda x: x * 2 to each element in l. This is equivalent to:
Copydef timesTwo(x):
return x * 2
l = map(timesTwo, l)
Note that map() returns a map object, not a list, so if you really need a list afterwards you can use the list() function afterwards, for instance:
Copyl = list(map(timesTwo, l))
Thanks to Minyc510 in the comments for this clarification.
Answer from APerson on Stack OverflowTry a list comprehension:
Copyl = [x * 2 for x in l]
This goes through l, multiplying each element by two.
Of course, there's more than one way to do it. If you're into lambda functions and map, you can even do
Copyl = map(lambda x: x * 2, l)
to apply the function lambda x: x * 2 to each element in l. This is equivalent to:
Copydef timesTwo(x):
return x * 2
l = map(timesTwo, l)
Note that map() returns a map object, not a list, so if you really need a list afterwards you can use the list() function afterwards, for instance:
Copyl = list(map(timesTwo, l))
Thanks to Minyc510 in the comments for this clarification.
The most pythonic way would be to use a list comprehension:
Copyl = [2*x for x in l]
If you need to do this for a large number of integers, use numpy arrays:
Copyl = numpy.array(l, dtype=int)*2
A final alternative is to use map
Copyl = list(map(lambda x:2*x, l))
List multiplication with a scalar
Multiplying each integer in a list of lists by a float
How to multiply each row of dataframe by a ratio depending on a set of conditions
NumPy: How to scale a rectangular array by a vector of scalars?
Videos
ar = [0] * 3 ar[0] = 10 print(ar) # 10, 0, 0
ar = [ [0] * 3 ] * 3 ar[0][0] = 10 print(ar) # 10, 0, 0 , 10, 0, 0 , 10, 0, 0
-
operator on list creates n references to the same list hence the second case is digestible. But if that's the case why don't in 1d list we are getting 10, 10, 10?