Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting last element of range in Python

This may be an easy question, but could you tell me how I can print the last element in a range, please ? I did in this way:

for j in range (3):
    print(j[2:])      # I only wish to print 2 here

But it says

TypeError: 'int' object is not subscriptable

Could you tell me how to I can get it with this range function, please ?

like image 337
user_01 Avatar asked Sep 13 '25 00:09

user_01


1 Answers

Range returns a list counting from 0 to 2 (3 minus 1) ([0, 1, 2]), so you can simply access the element directly from the range element. Index -1 refers to the last element.

print(range(3)[-1])
like image 121
Neil Avatar answered Sep 15 '25 15:09

Neil