In Python, if I multiply of list of objects by an integer, I get a list of references to that object, e.g.:
>>> a = [[]] * 3
>>> a
[[], [], []]
>>> a[0].append(1)
>>> a
[[1], [1], [1]]
If my desired behavior is to create a list of copies of the original object (e.g. copies created by the "copy.copy()" method or something sort of standard, is there an elegant way to do this with the same multiplication operator? Or should I just stick with a list comprehension or something? E.g.
[[] for x in range(0,3)]
Any version of Python is fine.
Multiplication between two equal length lists multiplies each element from one list by the element at the same index in the other list. For example, multiplying [1, 2, 3] and [4, 5, 6] results in [4, 10, 18] .
We can use numpy. prod() from import numpy to get the multiplication of all the numbers in the list. It returns an integer or a float value depending on the multiplication result.
Python provides the operator x *= y to multiply two objects in-place by calculating the product x * y and assigning the result to the first operands variable name x .
Multiply two lists using for loop Through for loop, we can iterate through the list. Similarly, with every iteration, we can multiply the elements from both lists. For this purpose, we can use Zip Function. The zip() function in python can combine the contents of 2 or more iterables.
This is a good usage of list comprehension - its also the most readable way to do it IMO.
So the [[] for x in range(0,3)]
you suggest isn't the multiplication operator, but gets the result you want.
The multiplication operator on a sequence means repetition of the item(s) -- NOT creation of copies (shallow or deep ones) of the items. Nothing stops you from going crazy, a la:
import copy
class Crazy(object):
def __init__(self, body, weird=copy.copy):
self.gomez = body
self.cousinitt = weird
def __mul__(self, n):
return [self.cousinitt(x) for x in (self.gomez * n)]
a = Crazy([[]]) * 3
...except your sanity and common sense, if any. Checking on those, how DID you dream operator *
could be made to mean something utterly different than it's intended to mean, except by defining another class overloading __mul__
in weird ways...?-)
The list comprehension is the best way to do this. If you define a new class and overload the * operator, it will seriously confuse the next person to read the code.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With