Is there a way to get the last number from the range()
function?
I need to get the last number in a Fibonacci sequence for first 20 terms or should I use a list instead of range()
?

- 530,221
- 131
- 937
- 1,214
5 Answers
Not quite sure what you are after here but here goes:
rangeList = range(0,21)
lastNumber = rangeList[len(rangeList)-1:][0]
or:
lastNumber = rangeList[-1]

- 42,006
- 17
- 96
- 122
by in a range, do you mean last value provided by a generator? If so, you can do something like this:
def fibonacci(iterations):
# generate your fibonacci numbers here...
[x for x in fibonacci(20)][-1]
That would get you the last generated value.

- 5,185
- 25
- 41
I don't think anyone considered that you need fibonacci numbers. No, you'll have to store each number to build the fibonacci sequence recursively, but there is a formula to get the nth term of the fibonacci sequence.
If you need the last number of a list, use myList[-1].

- 66,414
- 68
- 253
- 406
-
interesante también, muchas gracias – Apr 23 '09 at 02:29
Python range
s are subscriptable and can calculate indices without generating all the numbers:
range(1, 10**10, 3)[-1]
will return instantly.
The actual computation for r = range(start, stop, step)
is something like r.start + (len(r) - 1) * r.step
(len(r)
is computed in constant time and this assumes len(r) > 0
)

- 9,525
- 5
- 58
- 102
Is this what you're after?
somerange = range(0,20)
print len(somerange) # if you want 20
print len(somerange)-1 # if you want 19
now if you want the number or item contained in a list...
x = [1,2,3,4]
print x[len(x)-1]
# OR
print x[-1] # go back 1 element from current index 0, takes you to list end

- 23,735
- 11
- 56
- 82
-
thanks for answer but with for i in range(0,21): print all numbers 0,1,2... and i need only the last 20 for the example – Apr 23 '09 at 02:19