Contents
Kinh Nghiệm về Python declare list Chi Tiết
Quý khách đang tìm kiếm từ khóa Python declare list được Update vào lúc : 2022-01-25 14:02:20 . Với phương châm chia sẻ Bí kíp về trong nội dung bài viết một cách Chi Tiết 2022. Nếu sau khi đọc tài liệu vẫn ko hiểu thì hoàn toàn có thể lại Comment ở cuối bài để Mình lý giải và hướng dẫn lại nha.
Initialize a list with given size and values in Python
Posted: 2022-10-19 / Tags: Python, ListTweet
This article describes how to initialize a list with an any size (number of elements) and values in Python.
Nội dung chính
- Initialize a list with given size and values in PythonCreate an empty listInitialize a list with an any size and valuesNotes on initializing a 2D list (list of lists)For tuples and arraysRelated CategoriesRelated ArticlesVideo liên quan
- Create an empty listInitialize a list with an any size and valuesNotes on initializing a 2D list (list of lists)For tuples and arrays
See the following article about initialization of NumPy array ndarray.
- NumPy: Create an ndarray with all elements initialized with the same value
Sponsored Link
Create an empty list
An empty list is created as follows. You can get the number of elements of a list with the built-in function len().
l_empty = []
print(l_empty)
# []
print(len(l_empty))
# 0
source: list_initialize.py
You can add an element by append() or remove it by remove().
l_empty.append(100)
l_empty.append(200)
print(l_empty)
# [100, 200]
l_empty.remove(100)
print(l_empty)
# [200]
source: list_initialize.py
See the following articles for details on adding and removing elements from lists,
- Add an item to a list in Python (append, extend, insert)Remove an item from a list in Python (clear, pop, remove, del)
Initialize a list with an any size and values
As mentioned above, in Python, you can easily add and remove elements from a list, so there are few situations where you need to initialize a list in advance.
If you want to initialize a list of any number of elements where all elements are filled with any values, you can use the * operator as follows.
l = [0] * 10
print(l)
# [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
print(len(l))
# 10
source: list_initialize.py
A list is generated that repeats the elements of the original list.
print([0, 1, 2] * 3)
# [0, 1, 2, 0, 1, 2, 0, 1, 2]
source: list_initialize.py
You can generate a list of sequential numbers with range().
- How to use range() in Python
Sponsored Link
Notes on initializing a 2D list (list of lists)
Be careful when initializing a list of lists.
The following code is no good.
l_2d_ng = [[0] * 4] * 3
print(l_2d_ng)
# [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]
source: list_initialize.py
If you update one list, all the lists will be changed.
l_2d_ng[0][0] = 5
print(l_2d_ng)
# [[5, 0, 0, 0], [5, 0, 0, 0], [5, 0, 0, 0]]
l_2d_ng[0].append(100)
print(l_2d_ng)
# [[5, 0, 0, 0, 100], [5, 0, 0, 0, 100], [5, 0, 0, 0, 100]]
source: list_initialize.py
This is because the inner lists are all the same object.
print(id(l_2d_ng[0]) == id(l_2d_ng[1]) == id(l_2d_ng[2]))
# True
source: list_initialize.py
You can write as follows using list comprehensions.
- List comprehensions in Python
l_2d_ok = [[0] * 4 for i in range(3)]
print(l_2d_ok)
# [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]
source: list_initialize.py
Each inner list is treated as a different object.
l_2d_ok[0][0] = 100
print(l_2d_ok)
# [[100, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]
print(id(l_2d_ok[0]) == id(l_2d_ok[1]) == id(l_2d_ok[2]))
# False
source: list_initialize.py
Although range() is used in the above example, any iterable of a desired size is acceptable.
l_2d_ok_2 = [[0] * 4 for i in [1] * 3]
print(l_2d_ok_2)
# [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]
l_2d_ok_2[0][0] = 100
print(l_2d_ok_2)
# [[100, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]
print(id(l_2d_ok_2[0]) == id(l_2d_ok_2[1]) == id(l_2d_ok_2[2]))
# False
source: list_initialize.py
If you want to generate a multidimensional list, you can nest list comprehensions.
l_3d = [[[0] * 2 for i in range(3)] for j in range(4)]
print(l_3d)
# [[[0, 0], [0, 0], [0, 0]], [[0, 0], [0, 0], [0, 0]], [[0, 0], [0, 0], [0, 0]], [[0, 0], [0, 0], [0, 0]]]
l_3d[0][0][0] = 100
print(l_3d)
# [[[100, 0], [0, 0], [0, 0]], [[0, 0], [0, 0], [0, 0]], [[0, 0], [0, 0], [0, 0]], [[0, 0], [0, 0], [0, 0]]]
source: list_initialize.py
For tuples and arrays
You can initialize tuples as well as lists.
Note that a tuple of one element requires ,.
- One-element tuples require a comma in Python
t = (0,) * 5
print(t)
# (0, 0, 0, 0, 0)
source: list_initialize.py
For array type, you can pass the initialized list to the constructor.
- array Efficient arrays of numeric values Python 3.9.0 documentation
import array
a = array.array(‘i’, [0] * 5)
print(a)
# array(‘i’, [0, 0, 0, 0, 0])
source: list_initialize.pySponsored LinkShareTweet
Related Categories
- PythonList
Related Articles
- Transpose 2D list in Python (swap rows and columns)Remove / extract duplicate elements from list in PythonExtract and replace elements that meet the conditions of a list of strings in PythonCartesian product of lists in Python (itertools.product)Convert lists and tuples to each other in PythonHow to slice a list, string, tuple in PythonConvert 1D array to 2D array in Python (numpy.ndarray, list)Extract, replace, convert elements of a list in PythonReverse a list, string, tuple in Python (reverse, reversed)enumerate() in Python: Get the element and index from a listzip() in Python: Get elements from multiple listsAdd an item to a list in Python (append, extend, insert)Swap values in a list or values of variables in Pythonin operator in Python (for list, string, dictionary, etc.)Convert a list of strings and a list of numbers to each other in Python
Review Python declare list ?
Bạn vừa đọc Post Với Một số hướng dẫn một cách rõ ràng hơn về Clip Python declare list tiên tiến và phát triển nhất
Heros đang tìm một số trong những ShareLink Tải Python declare list Free.
Giải đáp vướng mắc về Python declare list
Nếu sau khi đọc nội dung bài viết Python declare list vẫn chưa hiểu thì hoàn toàn có thể lại Comments ở cuối bài để Admin lý giải và hướng dẫn lại nha
#Python #declare #list