5. Incrementing all elements

Screen Link:

My Code:

values = [16, 1, 7, 2, 19, 12, 5, 20, 2, 10, 10, 14, 17, 14, 1, 16, 19, 7, 9, 19]

for i in range(len(values)):
    values[i] += 1
    
print(values)

What I expected to happen: I got the answer and understood the logic, however if i want to know print(range(values) then it shows the following error

What actually happened:

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-1-c981508fbb4b> in <module>
      6 
      7 print(values)
----> 8 print(range(values))

TypeError: 'list' object cannot be interpreted as an integer
Any insight on this?

Hi

As per the docs,

Blockquote
The arguments to the range constructor must be integers (either built-in int or any object that implements the index special method). If the step argument is omitted, it defaults to 1. If the start argument is omitted, it defaults to 0. If step is zero, ValueError is raised.

And in the code

values is a list not an integer. Hence the error.

Hope its clear now.
Thanks.

2 Likes

Hi @uditchauhan,

Practically, you want to know the number of items in your list, i.e. its length, so use this instead: print(len(values)).

Otherwise, if you want, for some reason, to print exactly the range of values used in your for-loop, then use this piece of code, just directly taken from your for-loop: print(range(len(values))).

2 Likes

hey thanks for replying. I might need some time to process this

yess i tried print(len(values)) and got the length, however i was just experimenting to get the range and why there is an error and i wanted to understand it. Thanks to you both