0
how come the answer is 4 not 3?
I was doing the quiz, here is the question: What is the result of this code? nums = list(range(5)) print(nums[4]) For my understanding, list(range(5)) should be:[0,1,2,3,4] and the nums[4] should be :3 but when I put this code into code playground showed me 4 can anyone help to answer it, thank you!
4 Respuestas
+ 8
Davide , i would like to make some comments to your post, because there can be some misunderstandings. Your explanation is set in *** your text ***, and my comments does start with "--->".
***When you do range(N) you declare a length of 5 elements.***
---> This is confusing, because it implicates that “N” creates 5 elements. When we use range(N) we create a range object that can generate “N” elements.
---> range() function is used to generate a sequence of numbers. But the numbers themselves are not stored in the range object, they will be created on the fly during an iteration on the range object or when the range object is converted to an iterable.
***But when you later call the elements by "name" you need to keep in mind that the name of the first is 0, for the second is 1 and so on. so in your case, you are calling the element named 4, which is the 5th element.In general the name of the n-th element is n-1***
---> to address a single element in an iterable like list, we use the term “index” not “name".
0
When you do range(N) you declare a length of N elements.
But when you later call the elements by "name" you need to keep in mind that the name of the first is 0, for the second is 1 and so on
In general the name of the n-th element is n-1
so in your case, you are calling the element named 4, which is the 5th element
0
Lothar i corrected the 5 with the N. It was obviously just a slip.
For the other stuff, I only tried to help the OP to understand. I wasn't trying to be a textbook.
0
The indexing starts with 0 so the 4th index is actually the 5th item in the list. Hope this helps