Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does '[0]' mean in Python?

Tags:

python

arrays

I'm familiar with programming but new to python:

mem = [0] * memloadsize

what does the '[0]' represent? Is it a built-in array?

like image 464
Sean Avatar asked Sep 20 '12 21:09

Sean


2 Answers

The [ and ] characters, in this context, are used to construct array literals:

>>> []
[]
>>> [0]
[0]
>>> ['a', 'b', 'c']
['a', 'b', 'c']

Multiplying arrays is idiomatic, and generates an array gotten by repeating the elements in the array by the given factor:

>>> ['a'] * 4
['a', 'a', 'a', 'a']
>>> [0] * 9
[0, 0, 0, 0, 0, 0, 0, 0, 0]
>>> [0, 1, 2] * 2
[0, 1, 2, 0, 1, 2]

Note that [ and ] are also used to index into an existing array. In that case, [0] accesses the first element in the array:

>>> a = ['first', 'second', 'third']
>>> a[0]
'first'
>>> a[2]
'third'
>>> 
like image 127
Claudiu Avatar answered Oct 01 '22 16:10

Claudiu


It just means a one element list containing just a 0. Multiplying by memloadsize gives you a list of memloadsize zeros.

like image 30
MAK Avatar answered Oct 01 '22 16:10

MAK