Python list : Create and Initialize
In Python, a list is an ordered collection (a sequence) that can store elements of different data types like numbers, strings, and objects.
Methods of Initializing Lists
Creating an Empty List
You create an empty list using []
.
1empty_list = []
Creating a List with Specific Values
To create a list with specific values, you write these values, separated by commas, inside square brackets.
1value_list = [1, 2, 3, 4, 5]
Creating a List with a Specific Number of Elements
You can create a list with a specific number of elements using the *
operator. This way, you can specify the length of the list and assign the same value to all elements.
1# A list of length 10 with 0 as its element
2same_value_list = [0] * 10
Creating a List Using the Values of Other Variables
You can also create a list using the values of other variables.
1x = 3
2y = 4
3z = 5
4
5variable_list = [x, y, z]
Special Methods for Initializing Lists
Initializing a List Using List Comprehension
List comprehension is a characteristic of Python that allows you to write shorter code and is often used when initializing lists.
1# Initialize a list with numbers from 0 to 9
2list_comprehension = [i for i in range(10)]
Initializing a List Using the List Function
You can also initialize a list using the
list()
function. This method is used when you want to convert another data type (like a tuple or string) into a list.
1# Convert a string to a list
2str_to_list = list("Hello, Python!")
Creating a List with Multiple Values
To create a list with multiple values, you separate the values with commas.
1multi_value_list = [1, 2, 3, 4, 5]
Initializing a List by Directly Entering Numbers
You can also create a list by directly entering numbers.
1number_list = [123, 456, 789]
Initializing a List by Directly Entering Strings
You can also create a list by directly entering strings.
1str_list = ["Apple", "Banana", "Cherry"]
Cautions
Initializing Multidimensional Lists
When initializing multidimensional lists (lists of lists), you need to be careful. In particular, when initializing a multidimensional list with the same values, you should use list comprehension to ensure that each sublist doesn’t reference the same object.
If you initialize as follows, the sublists will reference the same object, and if you change part of it, the other parts will also change.
1# Incorrect way of initializing a multidimensional list
2wrong_multi_list = [[0]*3]*3
3wrong_multi_list[0][0] = 99
4print(wrong_multi_list) # Outputs: [[99, 0, 0], [99, 0, 0], [99, 0, 0]]
The correct way to initialize is as follows.
1# Correct way of initializing a multidimensional list
2correct_multi_list = [[0]*3 for _ in range(3)]
3correct_multi_list[0][0] = 99
4print(correct_multi_list) # Outputs: [[99, 0, 0], [0, 0, 0], [0, 0, 0]]