Getting last element of range in Python
15,658
Solution 1
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])
Solution 2
I the range is in your collection you should be able to reference that object directly by the index.
if len(j) > 2:
print("Value: " + j[2])
Author by
user_01
Updated on June 04, 2022Comments
-
user_01 almost 2 years
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 ?
-
zondo about 7 yearsIf you don't need a
for
loop; just usej = range(3)
instead offor j in range(3)
. -
user_01 about 7 yearsI need to use for loop, unfortunately
-
McGrady about 7 yearsPossible duplicate of Getting the last element of a list in Python
-
zondo about 7 yearsThen assign a variable before the loop, say
numbers = range(3)
; change the loop tofor j in numbers:
, and useprint(numbers[-1])
-
Paul Rooney about 7 yearsUsing a for loop makes no sense, since you don't need to iterate over the collection, you just need to get the last element.
-