Reputation: 23
Just want to understand the logic of using - range(len()) for the purpose of indexing
for eg. i have mylist=[1,2,3,4,5]
so here -> len(mylist)
would be 5
and range(len(mylist))
would be (0,5)
however the computer starts reading from 0
as position : making mylist 0 to 4
where mylist[4]= 5
so here do we use range(len(mylist)-1
to set the range correctly for the purpose of indexing ?
apologies if i am not clear (beginner)
Thanks.
Upvotes: 1
Views: 1044
Reputation: 5479
Remember that the length of the list is always one greater than it's last index. In your exmaple, the length of the list is 5, whereas the final index is 4. So when you say range(len(my_list)), the range that stops one short compensates for the len that is one too long. It all works out nicely so that you iterate through all items of the list by range(len(my_list)).
Upvotes: 0
Reputation: 37049
Let's look at just range
.
Check out what the help section says. You can get to help from your terminal by typing python3
and then typing help(range)
. To get out of the help, press q
. To get out of the terminal, type quit()
.
% python3
Python 3.9.1 (default, Dec 28 2020, 11:25:16)
[Clang 12.0.0 (clang-1200.0.32.28)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> help(range)
Here's the relevant help area:
Help on class range in module builtins:
class range(object)
| range(stop) -> range object
| range(start, stop[, step]) -> range object
|
| Return an object that produces a sequence of integers from start (inclusive)
| to stop (exclusive) by step. range(i, j) produces i, i+1, i+2, ..., j-1.
| start defaults to 0, and stop is omitted! range(4) produces 0, 1, 2, 3.
| These are exactly the valid indices for a list of 4 elements.
| When step is given, it specifies the increment (or decrement).
If you were to type:
for item in range(5):
print(item)
You will get 0, 1, 2, 3 and 4.
Range takes start, stop and step as an argument. Start, if not provided, is zero. Zero is inclusive. We provided stop of 5. But note that 5 is exclusive. That means, range will print from 0 and stop before 5.
Your list mylist = [1, 2, 3, 4, 5]
has 5 items. To access the first item, you'd write mylist[0]
. To get to the last item, you'd write mylist[4]
.
Instead of typing range(5)
, you can as well type range(len(mylist))
, len(mylist) is 5.
Let's say you typed this code in test.py
mylist = [1,2,3,4,5]
for index in range(5):
print(f'Range = {index} and mylist item is {mylist[index]}')
If you run it, this is what you'll see:
python3 test.py
Range = 0 and mylist item is 1
Range = 1 and mylist item is 2
Range = 2 and mylist item is 3
Range = 3 and mylist item is 4
Range = 4 and mylist item is 5
Notice how we went from mylist[0] through mylist[4] using range(5), wherein range(5) gave us numbers from 0 to 4.
Feel free to ask follow-up questions in comments.
Upvotes: 1