This guide explains how to use Python's range() and len() functions to maximize efficiency while writing code.
Introduction
Python's range() and len() functions are useful tools for optimizing code and increasing productivity. range() allows you to select portions of a sequence by providing numerical boundaries, whereas len() helps you to figure out the length of a sequence quickly and accurately.
Usage
range()
Syntax
range(start, stop[, step])
Explanation
The range() function creates a sequence of numbers. The first parameter start
is the beginning of the sequence and the second parameter stop
is the number immediately after the last number in the sequence. The sequence can also be specified with a third parameter step
which is the amount added to each number as the sequence progresses. The default value for step is 1.
Examples
For example, if you want to create a sequence of numbers from 1 to 10, you would enter
range(1, 11)
to get the following sequence:
(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
Using the step
parameter, if you only wanted to get odd numbers from 1 to 10, you would use
range(1, 11, 2)
to get the following sequence:
(1, 3, 5, 7, 9)
len()
Syntax
len(object)
Explanation
The len() function returns the length of an object. It is useful for determining the length of a sequence, iterable, or related object.
Examples
For example, if you wanted to get the length of the list below, you would use
list = [3, 5, 7, 8, 10]
len(list)
to get the following output:
5
FAQ
Q: Can I use the range() function with negative numbers?
A: Yes, you can use the range() function with negative numbers as long as your stop
parameter is greater than the start
parameter.
Q: What happens when I try to use the len() function with a string?
A: The len() function will return the length of a string in terms of the number of characters in the string.