Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Complex syntax- Python

Tags:

python

syntax

I am quite new to programming and don't understand a lot of concepts. Can someone explain to me the syntax of line 2 and how it works? Is there no indentation required? And also, where I can learn all this from?

string = #extremely large number

num = [int(c) for c in string if not c.isspace()]
like image 950
Hummus Avatar asked Sep 13 '12 19:09

Hummus


2 Answers

That is a list comprehension, a sort of shorthand for creating a new list. It is functionally equivalent to:

num = []
for c in string:
    if not c.isspace():
       num.append(int(c))
like image 197
mgilson Avatar answered Oct 18 '22 02:10

mgilson


It means exactly what it says.

num   =        [          int(                      c)

"num" shall be a list of: the int created from each c

for   c                           in string

where c takes on each value found in string

if        not                     c .isspace() ]

such that it is not the case that c is a space (end of list description)
like image 34
Karl Knechtel Avatar answered Oct 18 '22 02:10

Karl Knechtel