Python – Using the Multiply Operator to Create Copies of Objects in Lists

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.

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

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.

Method 2

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…?-)

Method 3

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.


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x