Creating an Empty List of a Specific Size in Python
In Python, one can create a list using various methods. One common question is how to create an empty list that can hold a predetermined number of elements.
To address this, let's consider the following code:
xs = list() for i in range(0, 9): xs[i] = i
This code attempts to create an empty list and then assign values to it. However, it results in an IndexError because one cannot assign to an element in an empty list without first initializing it.
Solution:
To create an empty list of a specific size, one can use list comprehension. For example, to create a list of 10 elements, one can do the following:
xs = [None] * 10
This code creates a list with 10 None values, which can then be assigned with any desired values.
xs[1] = 5
Alternatively, one can use the range() function, which creates a sequence of numbers. In Python 2.X, one can use range(10), while in Python 3.X, one should use list(range(10)).
# 2.X only. Use list(range(10)) in 3.X. xs = range(10)
Another option is to use a function to create the list.
def display(): xs = [] for i in range(9): # This is just to tell you how to create a list. xs.append(i) return xs
Finally, one can also use list comprehension to create a list with specific values.
def display(): return [x**2 for x in range(9)]
The above is the detailed content of How Do I Create an Empty List of a Specific Size in Python?. For more information, please follow other related articles on the PHP Chinese website!