3

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

1 Answer 1

7

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)]
Sign up to request clarification or add additional context in comments.

4 Comments

I knew there'd be a "python" way! Thanks.
@nickf Note that the resulting list has maxCols references to the same objects. With mutable objects, this leads to quite different (and almost never desriable) semantics.
To further clarify/illustrate: [[]] * maxCols list will actually contain maxCols "references" to the same list.
@delnan: I was just updating the answer with that. Good catch :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.