What does the [0]*x syntax do in Python? What does the [0]*x syntax do in Python? python python

What does the [0]*x syntax do in Python?


The [0] * x creates a list with x elements. So,

>>> [ 0 ] * 5[0, 0, 0, 0, 0]>>> 

Be warned that they all point to the same object. This is cool for immutables like integers but a pain for things like lists.

>>> t = [[]] * 5>>> t[[], [], [], [], []]>>> t[0].append(5)>>> t[[5], [5], [5], [5], [5]]>>> 

The ** operator is used for exponentation.

>>> 5 ** 2 25


The x = [0] * n is demonstrated here:

>>> [0]*10[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]

It 'multiplies' the list elements

>>> [1, 2, 3] * 3[1, 2, 3, 1, 2, 3, 1, 2, 3]

The ** is the power operator

>>> 3**29

Although be careful, it can also be **kwargs (in a different context), see more about that here Proper way to use **kwargs in Python


  1. X =[0] * N, produces a list of size N, with all N elements being the value zero. for example, X = [0] * 8, produces a list of size 8.

    X = [0, 0, 0, 0, 0, 0, 0, 0]

    Pictorial representation will be like,

The result of command [0] * 8

Technically, all eight cells of the list reference the same object. This is because of the fact that lists are referential structures in python.

and, if you try to assign a new value to list, say X[2] = 10, this does not technically change the value of the existing integer instance. This computes a new integer, with value 10, and sets cell 2 to reference the newly computed value.

Pictorial representation,

enter image description here

  1. ** is power operator and computes the power of a number. for example, 5 ** 2 results in 25.