How do I set a variable to a index of a list?
Let's explain what your code does before solving it. Edit available at the bottom of the answer
for i in range(3):
a = l[i]
What this does is creates a "range" of numbers from 0 to 2, however its supposed to go from 1 (or 0) to 3. Why? Computers have been trained to start counting from 0 instead of 1 like a normal human and subsequently they are 1 less. (This is a simplified one, there's a longer one that you'll learn over time) Now your 2nd line of code assigns the variable a the value of one of the items in the list l. Let's look at what value 'a' would be assigned during this time
1 (1st item)
2 (2nd item)
IndexError: Out of range error (there is no 3rd item)
So how do you solve this? One way is to add more items to your list l. So let's then add 2 more items into l (3 and 4) This is our variable l now
l = [1, 2, 3, 4]
Here's our output now
1 (1st item)
2 (2nd item)
3 (3rd item)
As you noticed, it skips the 4th item since we specified to only iterate over 3 items in the list. If you wanted to "iterate over a list" look no further!.
Observe
for i in l:
print(i)
This creates a for loop that goes over each item in the list l one by one from start to finish that allows you to see the current item in the variable i! In our code, it simply prints the variable i each time the for loop goes to the next item in the list.
1
2
3
4
And simply stops once it reaches the end! Don't worry, we've all been there while learning code :)
UPDATE: Based on what you were saying, I'm assuming if you wanted to assign the variable a the 2nd place in the list 'l' you would use
a = l[1]
Yes to get the 2nd place you need to type 1. The same goes for accessing the 1st item, you change the l[1] with l[0]. This is because computers count from 0 instead of human's traditionally counting from 1