4

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 ?

5
  • 1
    If you don't need a for loop; just use j = range(3) instead of for j in range(3). Commented Apr 6, 2017 at 2:51
  • I need to use for loop, unfortunately Commented Apr 6, 2017 at 2:55
  • 1
    Possible duplicate of Getting the last element of a list in Python Commented Apr 6, 2017 at 2:55
  • Then assign a variable before the loop, say numbers = range(3); change the loop to for j in numbers:, and use print(numbers[-1]) Commented Apr 6, 2017 at 2:56
  • Using a for loop makes no sense, since you don't need to iterate over the collection, you just need to get the last element. Commented Apr 6, 2017 at 2:59

3 Answers 3

17

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])
Sign up to request clarification or add additional context in comments.

Comments

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])

Comments

0

This loop will go through the list and check if it is the last item, if true, then print the message underneath.

num_list = [28, 27, 26, 25, 24, 23, 22]
 
 for i in range(len(num_list)):

    print(num_list[i])
    if num_list[-1] == num_list[i]:
        print ('last number: ' + str(num_list[i]))`

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.