Change a value in a list of lists

In the previous post we discussed iterating through a list of lists for accessing values. But what about assigning values?

Of course because of mutation the following code definitely works:

for i in range(len(listOfLists)):
  for j in range(len(listOfLists[i])):
    listOfLists[i][j] = 1

but what about this one?

for row in listOfLists:
  for j in range(len(row)):
    row[j] = 2

It works also!
And now, what about this one?

for row in listOfLists:
  for cell in row:
    cell = 3

No, that does not work!
That’s an example of Python mutation (see it here). For me it’s easier to understand it if I think about lists as memory pointers.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s