nickf
nickf

Reputation: 546015

How to initialize a list to a certain value in Python

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))

Upvotes: 3

Views: 702

Answers (1)

ᅠᅠᅠ
ᅠᅠᅠ

Reputation: 66940

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)]

Upvotes: 7

Related Questions