Archive

Posts Tagged ‘lists’

Create an array of size N and initialize its values

March 1, 2013 Leave a comment

Problem
Create an array of size 10 and initialize all values to 0.

Solution
So far, I’ve done it like this (and I was proud of myself :))

li = [0 for _ in range(10)]

But the Pythonic way is this:

li = [0] * 10

Ehh :) Actually this creates 10 identical “[0]” lists and concatenates them. Lists can be concatenated by the way:

>>> [1,2] + [3,4]
[1, 2, 3, 4]

See this reddit post for more tips.

Categories: python Tags: ,