I am having trouble understanding certain logic in Python.
Let’s say you have variable[i]. I do not understand the meaning of the [i] in the brackets or what variable[i] (temporary variable in brackets) is doing. Is it iterating over i??? is it iterating over variable???
Maybe I am blind, but I cannot find a forum simply explaining this logic and this is very hard for me to grasp. Please help!!!
If you have a list list_of_stuff = ["rock", "mouse", "tree"]
then list_of_stuff[0] would be "rock" list_of_stuff[1] would be "mouse" list_of_stuff[2] would be "tree"
You could use a loop to iterate through the list using each index too.
for i in range(3):
print(list_of_stuff[i])
range(3) iterates through integers 0, 1, 2 .
On the first iteration, i will be 0, so it’ll print what’s in list_of_stuff[0]
On the next iteration, i will be 1, so it’ll print what’s in list_of_stuff[1]
On the next iteration, i will be 2, so it’ll print what’s in list_of_stuff[2]
Example:
list_of_stuff = ["rock", "mouse", "tree"]
for i in range(3):
print(list_of_stuff[i] + f" << list_of_stuff[{i}]" + " when i is " + str(i))
You use similar stuff for a dictionary. dict1 = { "color" : "brown", "size" : "large" }
Here, dict1["size"]
would be "large"