7

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()]
6
  • 2
    That's a list comprehension. Yes, you can read about them at python.org. Commented Sep 13, 2012 at 19:05
  • 3
    This is called a list comprehension. One introduction: carlgroner.me/Python/2011/11/09/… Commented Sep 13, 2012 at 19:05
  • 1
    @Hannele - and since it is so routine, it is a great opportunity for an optimization. Commented Sep 13, 2012 at 19:26
  • 1
    To answer the one bit left over: There are no special indentation rules for list comprehensions. because this example is a single line, there is of course no indentation at all. If you want to split it over multiple lines, it follows the same Python rules as any other parenthesized or bracketed expression. For example, if you move for c in string and if not c.isspace() to their own lines, they should line up with the int(c). If you also move int(c) to a new line, it has to be indented farther than the num, and the other lines have to match its indentation. Commented Sep 13, 2012 at 20:23
  • 2
    PS, string isn't a great variable name, because it's the name of a module in the standard library. (And presumably it's not actually an extremely large number, but an extremely long string of digits; otherwise you'll get an error because 'int' object is not iterable.) Commented Sep 13, 2012 at 20:27

4 Answers 4

14

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))
Sign up to request clarification or add additional context in comments.

Comments

4

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)

Comments

1

Just to expand on mgilson's answer as if you're fairly new to programming, that can also be a bit obtuse. Since I started learning python a few months back, here's my annotations.

string = 'aVeryLargeNumber'
num = [int(c) for c in string if not c.isspace()] #list comprehension

"""Breakdown of a list comprehension into it's parts."""
num = [] #creates an empty list
for c in string: #This threw me for a loop when I first started learning
     #as everytime I ran into the 'for something in somethingelse':
     #the c was always something else. The c is just a place holder
     #for a smaller unit in the string (in this example). 
     #For instance we could also write it as:
     #for number in '1234567890':, which is also equivalent to 
     #for x in '1234567890': or 
     #for whatever in '1234567890'
             #Typically you want to use something descriptive.
     #Also, string, does not have to be just a string. It can be anything
     #so long as you can iterate (go through it) one item at a time
     #such as a list, tuple, dictionary.

if not c.isspace(): #in this example it means if c is not a whitespace character
        #which is a space, line feed, carriage return, form feed,
                #horizontal tab, vertical tab.

num.append(int(c))  #This converts the string representation of a number to an actual
        #number(technically an integer), and appends it to a list. 

'1234567890' # our string in this example
num = []
    for c in '1234567890':
        if not c.isspace():
            num.append(int(c))

The first iteration through the loop would look like:

num = [] #our list, empty for now
    for '1' in '1234567890':
        if not '1'.isspace():
            num.append(int('1'))

Note the ' ' around the 1. Anything between ' ' or " " means this item is a string. Although it looks like a number, as far as Python is concerned it isn't. An easy way to verify that is to type 1 + 2 in the interpreter and compare the result to '1' + '2'. See a difference? With numbers it adds them together as you'd expect. With strings it joins them together.

On to the second pass!

num = [1] #our list, now with a one appended!
    for '2' in '1234567890':
        if not '2'.isspace():
            num.append(int('2'))

And so it will continue until it runs out of characters in the string, or it produces an error. What would happen if the string was '1234567890.12345'? We can safely say that '.' isn't a whitespace character. So when we get down to int('.') Python is going to thrown an error:

Traceback (most recent call last):
    File "<string>", line 1, in <fragment>
builtins.ValueError: invalid literal for int() with base 10: '.'

As far as resources for learning Python, there's a lot of free tutorials such as:

http://www.learnpython.org

http://learnpythonthehardway.org/book

http://openbookproject.net/thinkcs/python/english3e

http://getpython3.com/diveintopython3

If you want to buy a book for learning then: http://www.amazon.com/Learning-Python-Powerful-Object-Oriented-Programming/dp/0596158068 is my favourite. Not sure why the ratings are low but I think the author does an excellent job.

Good luck!

Comments

0

These examples from the PEP are a good place to start. If you are not familiar with range and % you need to take a step back and learn more about the foundations.

>>> print [i for i in range(10)]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

>>> print [i for i in range(20) if i%2 == 0]
[0, 2, 4, 6, 8, 10, 12, 14, 16, 18]

>>> nums = [1,2,3,4]
>>> fruit = ["Apples", "Peaches", "Pears", "Bananas"]
>>> print [(i,f) for i in nums for f in fruit]
[(1, 'Apples'), (1, 'Peaches'), (1, 'Pears'), (1, 'Bananas'),
 (2, 'Apples'), (2, 'Peaches'), (2, 'Pears'), (2, 'Bananas'),
 (3, 'Apples'), (3, 'Peaches'), (3, 'Pears'), (3, 'Bananas'),
 (4, 'Apples'), (4, 'Peaches'), (4, 'Pears'), (4, 'Bananas')]
>>> print [(i,f) for i in nums for f in fruit if f[0] == "P"]
[(1, 'Peaches'), (1, 'Pears'),
 (2, 'Peaches'), (2, 'Pears'),
 (3, 'Peaches'), (3, 'Pears'),
 (4, 'Peaches'), (4, 'Pears')]
>>> print [(i,f) for i in nums for f in fruit if f[0] == "P" if i%2 == 1]
[(1, 'Peaches'), (1, 'Pears'), (3, 'Peaches'), (3, 'Pears')]
>>> print [i for i in zip(nums,fruit) if i[0]%2==0]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.