Arrays: Difference between revisions
Content deleted Content added
added pointer to Array |
m →{{header|Python}}: Correct mix-up of mutables/immutables |
||
Line 3,319: | Line 3,319: | ||
<lang python>myArray = [[0]* width] * height] # DOES NOT WORK AS INTENDED!!!</lang> |
<lang python>myArray = [[0]* width] * height] # DOES NOT WORK AS INTENDED!!!</lang> |
||
This creates a list of "height" number of references to one list object ... which is a list of width instances of the number zero. Due to the differing semantics of |
This creates a list of "height" number of references to one list object ... which is a list of width instances of the number zero. Due to the differing semantics of immutables (strings, numbers) and mutables (dictionaries, lists), a change to any one of the "rows" will affect the values in all of them. Thus we need to ensure that we initialize each row with a newly generated list. |
||
To initialize a list of lists one could use a pair of nested list comprehensions like so: |
To initialize a list of lists one could use a pair of nested list comprehensions like so: |