tags:

views:

188

answers:

5
abc = [0, ] * datalen;

"datalen" is an Integer.

Then I see referencing like this:

abc[-1]

Any ideas?

+8  A: 

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]
nosklo
Worth pointing out is that if it had been a tuple, you *would* need the comma: `(0,) * 5` is `(0, 0, 0, 0, 0)` while `(0) * 5` is `0`.
Blixt
A: 

creates a list with datalen number of zeroes

>>> datalen=5
>>> abc = [0, ] * datalen
>>> abc
[0, 0, 0, 0, 0]
piotr
+1  A: 

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'
Seth
+5  A: 

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.

raceCh-
+3  A: 

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'}]
>>> 
Stefano Borini
Very interesting, I guess that's because the dictionaries share the same object reference, when copying?
Wez
@KeyboardMonkey: it's because the multiplication operator repeats the reference to the same dictionary. What you see is a list of multiple views of the same dictionary, not different, independent dictionaries
Stefano Borini