Dereferencing lists inside list in Python

2024/12/9 22:19:25

When I define a list in a "generic" way:

>>>a=[[]]*3
>>>a
[[],[],[]]

and then try to append only to the second element of the outer list:

>>>a[1].append([0,1])
>>>a
[[[0,1]], [[0,1]], [[0,1]]]

it appends to all elements of the outer list as can be seen above, probably due to the fact that the elements are references to the same list and not different lists (why does it work that way?). How can I actually create a list in the same "generic" way, such that the inner lists would be different lists and not just references. Thanks.

Answer

You are correct, they are all references to one list.

[[] for _ in range(3)]

is a common way to create a list of independent empty lists. You can use xrange on Python 2.x, but it won't make a difference if the length is actually as small as in your example.

Not sure how to explain the reason for this (the reason is that it's implemented this way), but you can see that this behavior is documented (at least in passing) here:

Operation       Result                              Notes
s * n, n * s    n shallow copies of s concatenated  (2)

The word "shallow" here means exactly that: the elements are copied by reference. "Note 2" at the linked page also answers your question.

https://en.xdnf.cn/q/72778.html

Related Q&A

Unit test Theories in Python?

In a previous life I did a fair bit of Java development, and found JUnit Theories to be quite useful. Is there any similar mechanism for Python?Currently Im doing something like:def some_test(self):c…

how to do a nested for-each loop with PySpark

Imagine a large dataset (>40GB parquet file) containing value observations of thousands of variables as triples (variable, timestamp, value).Now think of a query in which you are just interested in …

Understanding an issue with the namedtuple typename and pickle in Python

Earlier today I was having trouble trying to pickle a namedtuple instance. As a sanity check, I tried running some code that was posted in another answer. Here it is, simplified a little more:from coll…

SQLAlchemy Columns result processing

Im working with a IBM DB2 database using ibm_db2 driver and sqlalchemy. My model is:class User(Model):id = Column(UID, Integer, primary_key=True)user = Column(USER, String(20))password …

How can I access relative paths in Python 2.7 when imported by different modules

The Goal: Access / Write to the same temp files when using a common utility function called from various python modules.Background: I am using the python Unittest module to run sets of custom tests tha…

Emacs: Inferior-mode python-shell appears lagged

Im a Python(3.1.2)/emacs(23.2) newbie teaching myself tkinter using the pythonware tutorial found here. Relevant code is pasted below the question.Question: when I click the Hello button (which should …

AttributeError: module spacy has no attribute load

import spacy nlp = spacy.load(en_core_web_sm)**Error:** Traceback (most recent call last):File "C:\Users\PavanKumar\.spyder-py3\ExcelML.py", line 27, in <module>nlp = spacy.load(en_core…

No module named Win32com.client error when using the pyttsx package

Today, while surfing on Quora, I came across answers on amazing things that python can do. I tried to use the pyttsx Text to Speech Convertor and that gave me an No module named Win32com.client error.T…

Python: How to create and use a custom logger in python use logging module?

I am trying to create a custom logger as in the code below. However, no matter what level I pass to the function, logger only prints warning messages. For example even if I set the argument level = log…

Flask-Mail - Sending email asynchronously, based on Flask-Cookiecutter

My flask project is based on Flask-Cookiecutter and I need to send emails asynchronously.Function for sending email was configured by Miguel’s Tutorial and sending synchronously works fine, but i don’…