1

Possible Duplicate:
How to initialize a list to a certain value in Python

In Java, I can do this:

int[] i = new int[5];

and all elements of i will be 0.

How can I do the same for python, I am doing like this:

i = [0, 0, 0 , 0, 0]

is there a cleaner/simpler way?

1
  • Incidentally, it is pretty rare occasion in python to have to initialize a list like that. It's much more common to use list comprehensions to build lists, or use the list's append() method. Commented Nov 16, 2012 at 1:34

3 Answers 3

4

You can use the * operator:

i = [0] * 5

Demo:

>>> i = [0] * 5
>>> i
[0, 0, 0, 0, 0]

Oh, and i is a bad naming choice. People expect i to be a numeric loop variable.

Sign up to request clarification or add additional context in comments.

Comments

2
i = [0] * 5

Warning: be careful when the things in the list are mutable objects, such as nested lists. You're making five references to the same object, which will bite you when you start manipulating the list items. With integers and strings, it's fine, though. For mutable objects:

i = [[] for _ in xrange(5)]   # range(5) on Python 3.x

Comments

1

Using a list comprehension:

i = [0 for j in range(5)]

You can also use this to build more complex arrays:

A = [[0 for i in range(5)] for j in range(5)]

1 Comment

A safer option, protecting you from: i = [[0]] * 5

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.