Reputation:
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()
?
Upvotes: 7
Views: 19992
Reputation: 10955
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
)
Upvotes: 0
Reputation: 5243
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.
Upvotes: 3
Reputation:
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
Upvotes: 0
Reputation: 67862
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].
Upvotes: 1
Reputation: 42532
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]
Upvotes: 13