Atlas
Atlas

Reputation: 1363

What does this python line mean?

abc = [0, ] * datalen;

"datalen" is an Integer.

Then I see referencing like this:

abc[-1]

Any ideas?

Upvotes: 2

Views: 458

Answers (5)

Stefano Borini
Stefano Borini

Reputation: 143925

In addition to what has been said, remember that this behavior is expected when you are copying mutable objects. Classic trap for new python programmers

>>> bc = [0,] * 5
>>> bc
[0, 0, 0, 0, 0]
>>> bc[2]=4
>>> bc
[0, 0, 4, 0, 0]


>>> bb = [{}, ]*5
>>> bb
[{}, {}, {}, {}, {}]
>>> bb[2]["hello"]="hi"
>>> bb
[{'hello': 'hi'}, {'hello': 'hi'}, {'hello': 'hi'}, {'hello': 'hi'}, {'hello': 'hi'}]
>>> 

Upvotes: 3

Krzysztof Bujniewicz
Krzysztof Bujniewicz

Reputation: 2417

As everyone else has said, [0] * n will give you a list of n zeros, and indexing with negative numbers with a[-k] gives k-th element from the end, like:


a[-1]

gives the last element of the sequence and


a[-3]

gives the third last element of the sequence.

Upvotes: 5

Seth
Seth

Reputation: 46463

When used in this context, * is the "sequence repetition" operator.

>>> datalen = 3
>>> abc = [0,] * datalen
[0, 0, 0]

In this case, it looks like it's being used as a way to create an array with datalen elements, all of which are initialized to zero.

This works for strings too (since they are also sequences):

>>> 'String' * 3
'StringStringString'

Upvotes: 1

piotr
piotr

Reputation: 5745

creates a list with datalen number of zeroes

>>> datalen=5
>>> abc = [0, ] * datalen
>>> abc
[0, 0, 0, 0, 0]

Upvotes: 0

nosklo
nosklo

Reputation: 223132

creates a list with datalen references to the object 0:

>>> datalen = 10
>>> print [0,] * datalen
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]

You don't really need the comma in there:

>>> print [0] * datalen
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]

Upvotes: 8

Related Questions