Home > python > Create an array of size N and initialize its values

Create an array of size N and initialize its values

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: ,
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: