W3docs

python

What is the output of 'list(range(5))' in Python?

Practice Your Knowledge

What is the output of 'list(range(5))' in Python?

Explanation

Understanding the Output of 'list(range(5))' in Python

The correct output of 'list(range(5))' in Python is [0, 1, 2, 3, 4]. This may seem puzzling at first if you are not familiar with Python's range() function and how it interacts with the 'list' constructor. Here's a detailed explanation to help understand it better.

Range Function in Python

The range() function in Python is a built-in function that generates a sequence of integers within a given range, starting from zero by default. The syntax for the range function is range(stop) or range(start, stop[, step]), where:

  • start: Optional. Specifies the starting point of the sequence. The default is 0.
  • stop: Required. Specifies the end point of the sequence. This number is not included in the sequence.
  • step: Optional. Specifies the increment between each number in the sequence. The default is 1.

When you write range(5), Python interprets this as a sequence of integers starting from 0 and ending before 5.

List Constructor in Python

In Python, we can generate a list from an iterable object using the list() constructor. The range object is an iterable object, so when we wrap range(5) with list(), it converts the range object into a list.

Therefore, list(range(5)) in Python would return a list of integers from 0 to 4 because Python uses zero-based indexing, meaning it starts counting from 0. So, the output would be [0, 1, 2, 3, 4].

Practical Application

This is particularly handy when you want to quickly generate a list of numbers without manually typing each one. For example, if you're iterating over a sequence of numbers in a for loop, you can use this combination to achieve it efficiently.

Here's an example where the range function is used to iterate over a sequence of numbers in a for loop:

for i in range(5):
    print(i)

The output will be:

0
1
2
3
4

Additional Tips

While Python's range() provides a quick way to create a list of numbers, the sequence it generates is not immediately displayed as a list. range(5) alone results in a range object, not the actual list of numbers. To visualize the full sequence as a list, you need to use the list() function, which converts the range object into a list of numbers, resulting in the output [0, 1, 2, 3, 4].

Understanding these nuances of Python is crucial for writing efficient code and makes working with data much easier and more efficient.

Want more like this? Take the full Python Basics quiz.

Start Quiz