FAQ: Learn Python: Python Lists and Dictionaries - More with 'for'

start_list = [5, 3, 1, 2, 4]

square_list =

for x in start_list:

square_list.append(x ** 2)

How does python know what “x” is? Where/how has it been defined?

We’re using the in keyword and for to iterate over all the values in the list. x is defined in the statement as the parameter to hold each value in turn…

Thanks! So if we were to just switch out all references to “x” in the code for “y” the result would be the same?

Yes. We can use any variable as the parameter of a for…in loop. It should not be a variable that is already in use.

Why does

.sort()

change the list’s variable?

list.sort() does not change the variable, only mutates the contents of the list so they are in either ascending order, or descending order relative to each other. The method sorts a list in place. The same variable is used to refer to it.

This will sound a little screwy, but in reality Python does not allow two same values to exist in memory at different locations. There are exceptions but in general terms, think of integers, small ones, anyway, as having a fixed place in memory that does not change.

>>> id(1)
140708874864288
>>> id(10)
140708874864576
>>> id(42)
140708874865600
>>> id(73)
140708874866592
>>> 

What we see above are the addresses in memory where those integers reside. They never move from their fixed locations.

Let’s create a list of those integers.

arr = [42, 73, 1, 10]

Now we’ll check the location of the list…

>>> id(arr)
1469287805632
>>> 

And now we check the ids of the contents…

>>> id(arr[0])
140708874865600    #  42
>>> id(arr[1])
140708874866592    #  73
>>> id(arr[2])
140708874864288    #  1
>>> id(arr[3])
140708874864576    #  10
>>> 

And now lets sort the array…

>>> arr.sort()
>>> id(arr)
1469287805632    #  location unchanged
>>> 

Checking the ids of the contents, once more…

>>> id(arr[0])
140708874864288    #  1
>>> id(arr[1])
140708874864576    #  10
>>> id(arr[2])
140708874865600    #  42
>>> id(arr[3])
140708874866592    #  73
>>> 

Finally,

>>> b = 73
>>> id(b)
140708874866592   # 73
>>> 

The value b refers to is not arr[3] but 73, at the same location.

1 Like