How does python create a list with a specified length and a specific value
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!