Quantcast
Channel: Planet Python
Viewing all articles
Browse latest Browse all 24375

Python Morsels: Data structures contain pointers

$
0
0

Data structures, like variables, contain references to objects, rather than the objects themselves.

Referencing the same object in multiple places

Let's point a variable row to a list of three zeroes:

>>> row=[0,0,0]

Now let's make a new variable that points to a list-of-lists:

>>> boat=[row,row,row]

We now have a list of three lists, each with three zeroes in it:

>>> boat[[0, 0, 0], [0, 0, 0], [0, 0, 0]]

What would happen if we look up index 1, and then index 1 again, and change that to the number 1?

>>> boat[1][1]=1

What do you think might happen? What will change in our lists?

We're looking up the second list, and then the second value in the second list, and assigning that value to 1. So we've asked to change the middle item in the middle list to the number 1.

That's not quite what happens though:

>>> boat[[0, 1, 0], [0, 1, 0], [0, 1, 0]]

Instead, we changed the middle number in all three of our inner lists.

Why did this happen?

Well...

Data structures store references, not objects

Lists in Python don't actually …

Read the full article: https://www.pythonmorsels.com/data-structures-contain-pointers/


Viewing all articles
Browse latest Browse all 24375

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>