Get the App
SLTechnology News&Howtos  ›  Development  › 

How does python create a list with a specified length and a specific value

Shulou Source: shulou.com Published: 2022-06-01 04:34:50 10月20日 Update

Editor to share with you how python to create a specified length and a specific value of list, I believe that most people do not know much about it, so share this article for your reference, I hope you can learn a lot after reading this article, let's go to know it!

How to create a list with a specified length and a specific value

Do not recommend way

List1 = [0,0,0,0,0,0,0,0,0,0,0,0] print list1# [0,0,0,0,0,0,0,0,0,0,0]

Recommended mode

List1 = [0] * 10print list1# [0,0,0,0,0,0,0,0,0,0,0]

In fact, the former approach does not conform to the DRY (Don't Repeat Yourself) principle at first glance, and you can see that there is a more elegant approach if you think about it. What if it's a tuple? Just change [0] to (0,), and don't forget the comma after 0. In addition, not only numbers are supported here, but it can actually be list or tuple made up of any object. For example:

Class User (object): passuser_list = [User ()] * 10 is all the content of the article "how to create list with specified length and specific value by python". 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: Length manner article content recommendation elegance not much practice principles most objects numbers more knowledge industry information information channels commas channels references Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno MySQL Linux Xiaomi Apple MariaDB