+ 1
What do the square brackets mean in the following: word = words[counter]
In the section on for loops, I don't understand what the following section means: word = words[counter] Here is the code of the exercise: words = ["hello", "world", "spam", "eggs"] counter = 0 max_index = len(words) - 1 while counter <= max_index: word = words[counter] print(word + "!") counter = counter + 1
2 Respuestas
+ 8
Where counter is a number,
words[counter] is referring to an index in the list. Check out this code.
Printing list manually without using loop.
https://code.sololearn.com/cc8376rHp6P1/?ref=app
+ 7
Remember how to get a value by the index of an array?
words = ["hello", "world"]
How do I get "hello"?
I'd say:
word = words[0]
Because "hello" is in the 0th index of the array. So I'm assigning the element in the 0th index of the array to the variable word.
This is the same thing that's happening in your question, counter is a number that represents the index of the array. Since counter is increasing after each print, you print each string in the array.
Expected output of your question:
hello!world!spam!eggs!
array = ["hello", "eggs", "spam", "cheese"]
index = 0 1 2 3
So, [indexNum] is just a way of getting an element by index in an array.