Get the App
SLTechnology News&Howtos  ›  Development  › 

How python initializes the list

Shulou Source: shulou.com Published: 2022-06-01 04:24:36 10月01日 Update

This article mainly shows you "python how to initialize the list", the content is easy to understand, clear, hope to help you solve your doubts, the following let the editor lead you to study and learn "how to initialize the list of python" this article.

Initialization list

If you want a list of 10 integer zeros, you may first think of:

Bag = [] for _ in range (10): bag.append (0)

Let's do it another way:

Bag = [0] * 10

Look, how elegant.

Note: if your list contains a list, doing so will result in a shallow copy.

For example:

Bag_of_bags = [[0]] * 5 # [[0], [0], [0], [0]] bag_of_bags [0] [0] = 1 # [[1], [1], [1], [1]]

Oops! All the lists have changed, and we just want to change the first list.

Change it:

Bag_of_bags = [[0] for _ in range (5)] # [[0], [0], [0], [0]] bag_of_bags [0] [0] = 1 # [[1], [0], [0], [0], [0]] these are all the contents of the article "how python initializes the list". Thank you for reading! I believe we all have a certain understanding, hope to share the content to help you, if you want to learn more knowledge, welcome to follow the industry information channel!

Tags: Content articles learning help elegance examples just copy integer way easy to understand more organization knowledge editing industry information information channels channels research Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno MySQL Microsoft MariaDB Huawei Docker