杰瑞科技汇

Python list(range)怎么用?

Of course! Let's break down list(range()) in Python, as it's a fundamental and very useful combination.

Python list(range)怎么用?-图1
(图片来源网络,侵删)

The Short Answer

list(range()) is a Python idiom used to generate a list of numbers. You use it when you need an actual list containing a sequence of integers, rather than just a range object.


The Three Parts: list, range, and

To understand how they work together, let's look at each piece individually.

range() - The Number Generator

The range() function by itself doesn't create a list. It creates a special, memory-efficient object called an iterable that represents a sequence of numbers. It generates these numbers on-the-fly as you loop through it, which is very fast and saves memory, especially for large ranges.

range() can be used in three main ways:

Python list(range)怎么用?-图2
(图片来源网络,侵删)

a) range(stop): Generates numbers from 0 up to (but not including) stop. This is the most common form.

# Generates numbers from 0 to 4
r = range(5)
print(r)          # Output: range(0, 5)  <-- This is the range object, not the list
print(type(r))    # Output: <class 'range'>
# To see the numbers, you must iterate over it
for number in r:
    print(number, end=' ') # Output: 0 1 2 3 4

b) range(start, stop): Generates numbers from start up to (but not including) stop. The start is inclusive, the stop is exclusive.

# Generates numbers from 5 up to 9
r = range(5, 10)
for number in r:
    print(number, end=' ') # Output: 5 6 7 8 9

c) range(start, stop, step): Generates numbers from start to stop, incrementing by step. The step can be positive or negative.

# Generates even numbers from 0 to 8
r = range(0, 10, 2)
for number in r:
    print(number, end=' ') # Output: 0 2 4 6 8
# Generates numbers counting down from 10 to 1
r = range(10, 0, -1)
for number in r:
    print(number, end=' ') # Output: 10 9 8 7 6 5 4 3 2 1

list() - The List Converter

The list() constructor takes any iterable (like a range object, a string, or another list) and creates a new list containing all the items from that iterable.

Python list(range)怎么用?-图3
(图片来源网络,侵删)
# Convert a string to a list of characters
my_string = "hello"
char_list = list(my_string)
print(char_list) # Output: ['h', 'e', 'l', 'l', 'o']
# Convert a tuple to a list
my_tuple = (1, 2, 3)
list_from_tuple = list(my_tuple)
print(list_from_tuple) # Output: [1, 2, 3]

- The Parentheses

The parentheses are used to call a function or, in this case, a constructor. So, range() calls the range function, and list() calls the list constructor.


Putting It All Together: list(range())

Now, let's combine them. When you wrap a range() object inside list(), you are telling Python:

  1. First, create a range object that represents a sequence of numbers.
  2. Then, immediately convert that entire sequence into a concrete list.

Examples

Example 1: Basic list of numbers

# Create a list of numbers from 0 to 4
number_list = list(range(5))
print(number_list)
# Output: [0, 1, 2, 3, 4]

Example 2: List with a start and stop value

# Create a list of numbers from 10 to 14
number_list = list(range(10, 15))
print(number_list)
# Output: [10, 11, 12, 13, 14]

Example 3: List with a step

# Create a list of the first 5 even numbers
even_numbers = list(range(0, 10, 2))
print(even_numbers)
# Output: [0, 2, 4, 6, 8]
# Create a list of the first 5 odd numbers
odd_numbers = list(range(1, 11, 2))
print(odd_numbers)
# Output: [1, 3, 5, 7, 9]

Example 4: Creating a list of a specific length

This is a very common pattern. If you need a list of a certain size (e.g., to initialize an array), list(range(n)) is a perfect way to do it.

# Create a list of 10 zeros (or any placeholder)
# We create a list of 10 numbers, then we can replace them
scores = list(range(10))
print(f"Initial list: {scores}") # Output: Initial list: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
# A more practical example: initializing a list with a specific value
# Create a list of 5 zeros
zeros = [0] * 5
print(f"Zeros list: {zeros}") # Output: Zeros list: [0, 0, 0, 0, 0]

Why Use list(range())? (When is it useful?)

You might wonder, "Why not just use a list comprehension like [i for i in range(5)]?" While that works, list(range()) is:

  1. More Readable and Idiomatic: It clearly expresses the intent: "give me a list of numbers in this range."
  2. More Efficient: list(range()) is implemented in C and is generally faster and more memory-efficient than a manual list comprehension for generating simple integer sequences.
  3. Essential for Slicing: You can't slice a range object in the same way you can a list. If you need a slice of a range as a list, you must convert it.
# You CAN slice a range object directly, but it returns another range
r = range(10)
sliced_range = r[2:7]
print(sliced_range)      # Output: range(2, 7)
# But if you need a LIST from that slice, you must convert it
sliced_list = list(r[2:7])
print(sliced_list)       # Output: [2, 3, 4, 5, 6]

Summary Table

Expression Output Type Use Case
range(5) range(0, 5) range object Memory-efficient representation for loops.
list(range(5)) [0, 1, 2, 3, 4] list When you need an actual list of numbers.
[x for x in range(5)] [0, 1, 2, 3, 4] list More flexible if you need to transform the numbers (e.g., [x*2 for x in range(5)]).
分享:
扫描分享到社交APP
上一篇
下一篇