1

So I have a very rudimentary understanding of python (10-week summer course split up between python and Matlab). I am trying to create a 2d list like so:

data.append (samples)
data.append (matches)
data_list.append (data)
data.clear()

This is running in a for loop and writing each time it iterates. However, when I run it and I print(data_list) I get an empty list.

I have successfully ran it like so:

data.append (samples)
data.append (matches)
data_list.append (data)
data = []

But I do not understand the difference between my two methods and why only the second one works...

4
  • Possible duplicate of What is an object reference in Python? Commented Jun 27, 2018 at 2:48
  • What is samples and matches? Commented Jun 27, 2018 at 2:51
  • data_list.append(data.copy()) will solve your issue. The problem is you're putting a reference to data inside data_list, not the stuff inside data. So when you clear data, the reference inside data_list is now pointing to an empty list. Commented Jun 27, 2018 at 2:51
  • samples and matches are integer values. Its a program that compares your birthday to a random sample group. So I understand how the data_list.append(data.copy()) solves this issue. It is strange that python handles that differently, because by clearing data by data=() is preserves the values in data_list however clearing by .clear it doesn't preserve the data. Commented Jun 27, 2018 at 2:56

1 Answer 1

5

In Python, it is critical to understand that everything is an object. Of these, you have two types:

  • immutable (int, float, char, str, tuple)
  • mutable (list, dict, other objects, ...)

Immutable objects cannot be changed. That is, you cannot redefine a immutable:

1 = 0

That is ridiculous! You may, however, bind immutables to names. We call such names "variables".

x = 1
y = x
x = 0

# x = 0
# y = 1

Mutable objects, however, may change their internal contents:

x = [0, 2]
y = x
x[0] = 1

# x = [1, 2]
# y = [1, 2]

Notice that y is merely a name to the list. When you mutate the list x with x[0] = 1, you are mutating the same list that y is bound to.


Why am I telling you all this? Because:

data.clear()

mutates the original list that data is bound to.

In contrast,

data = ()

simply rebinds data to some other object.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.