Python @ DjangoSpin

Python: Using the builtin function range()

Buffer this pageShare on FacebookPrint this pageTweet about this on TwitterShare on Google+Share on LinkedInShare on StumbleUpon
Reading Time: 1 minutes

Using range() in Python

Using range() in Python

In a lot of situations, you may feel the need to obtain a list of numbers, such as in for loop. The builtin function range(number) provides a list of integers from 0 to one less than the number provided. When used in the form range(lowerBound, upperBound), it returns a list of integers from lowerBound to one less than upperBound. Lastly, when used in the form range(lowerBound, upperBound, stepSize), it provides a list of integers from lowerBound to upperBound with the supplied step-size.

>>> range(4)
[0, 1, 2, 3]
>>> range(2, 7)
[2, 3, 4, 5, 6]
>>> range(0, 11, 2)
[0, 2, 4, 6, 8, 10]	
>>> range(10, 1, -1)
[10, 9, 8, 7, 6, 5, 4, 3, 2]


>>> myString = 'rendezvous'
>>> for characterPosition in range( len(myString) ):
	print( "Letter at index {} of {} is {}".format( characterPosition, myString, myString[characterPosition] ) )

Letter at index 0 of rendezvous is r
Letter at index 1 of rendezvous is e
Letter at index 2 of rendezvous is n
Letter at index 3 of rendezvous is d
Letter at index 4 of rendezvous is e
Letter at index 5 of rendezvous is z
Letter at index 6 of rendezvous is v
Letter at index 7 of rendezvous is o
Letter at index 8 of rendezvous is u
Letter at index 9 of rendezvous is s

See also:

Buffer this pageShare on FacebookPrint this pageTweet about this on TwitterShare on Google+Share on LinkedInShare on StumbleUpon

Leave a Reply