Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to initialize a list to a certain value in Python

Tags:

python

list

I'd like to get a list where each item is set to a certain value (in my case, 0). I've solved this in my code with the code below, but it feels so messy. Surely there's a better way?

maxWidths = map(lambda x: 0, range(0, maxCols))
like image 466
nickf Avatar asked Dec 02 '25 13:12

nickf


1 Answers

Multiply a one-element list by the desired length.

maxWidths = [0] * maxCols

In the above, all elements of the list will be the same objects. In case you're be creating a list of mutable values (such as dicts or lists), and you need them to be distinct, you can either use map as you did in the question, or write an equivalent list comprehension:

[[] for dummy in range(100)]
like image 89
Petr Viktorin Avatar answered Dec 04 '25 02:12

Petr Viktorin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!