Question

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()?

Was it helpful?

Solution

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]

OTHER TIPS

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.

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.

Binet's Formula

If you need the last number of a list, use myList[-1].

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
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top