Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

A flash question, I'm looking at the following code

from __future__ import division
import math
import time

def dft(x, inverse = False, verbose = False) :
    t = time.clock()
    N = len(x)
    inv = -1 if not inverse else 1
    X =[0] * N
    for k in xrange(N) :
        for n in xrange(N) :
            X[k] += x[n] * math.e**(inv * 2j * math.pi * k * n / N)
        if inverse :
            X[k] /= N
    t = time.clock() - t
    if verbose :
        print "Computed","an inverse" if inverse else "a","DFT of size",N,
        print "in",t,"sec."
    return X

and I'm wondering (I do not know python):

  • what does the X =[0] * N line do?
  • why the double asterisk ** ?
like image 206
Paul Avatar asked May 15 '11 10:05

Paul


People also ask

What does 0 ]* n mean in Python?

[0] * N creates a list of size N which contains only 0's. the ** is a notation for raising the left side to the power of right side.

What does X [: I mean in Python?

Meaning of X = X[:, 1] in Python is: X is a dataset or a array. Say Here X have n rows and n columns. so by doing x=x[:,1] we get all the rows in x present at index 1.

What does [- 1 :] mean in Python?

Python also allows you to index from the end of the list using a negative number, where [-1] returns the last element. This is super-useful since it means you don't have to programmatically find out the length of the iterable in order to work with elements at the end of it.

What does X for X in Python do?

This is just standard Python list comprehension. It's a different way of writing a longer for loop. You're looping over all the characters in your string and putting them in the list if the character is a digit.


1 Answers

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
like image 52
Noufal Ibrahim Avatar answered Sep 27 '22 22:09

Noufal Ibrahim