tags:

views:

64

answers:

4
+1  Q: 

python expression

I am new in python, and while reading a BeautifulSoup tutorial, I didn't understand this expression "[x for x in titles if x.findChildren()][:-1]" that i didn't understand? can you explain it

titles = [x for x in titles if x.findChildren()][:-1]
+5  A: 

To start with [:-1], this extracts a list that contains all elements except the last element.

>>> a=[1,2,3,4,5]
>>> a[:-1]
[1, 2, 3, 4]

The comes the first portion, that supplies the list to [:-1] (slicing in python)

[x for x in titles if x.findChildren()]

This generates a list that contains all elements (x) in the list "titles", that satisfies the condition (returns True for x.findChildren())

pyfunc
+1  A: 

It's called a for comprehension expression. It is simply constructing a list of all titles in the x list which return true when the findChildren function is called upon them. The final statement substracts the last one from the list.

wheaties
I've only ever known it to be called a list comprehension: http://docs.python.org/tutorial/datastructures.html#list-comprehensions . I've never heard it called a "for expression" before. From what language did you pick up that usage?
Jack Kelly
gah, i meant for comprehension and Scala
wheaties
+4  A: 

It's a list comprehension.

It's pretty much equivalent to:

def f():
    items = []
    for x in titles:
        if x.findChildren():
            items.append(x)
    return items[:-1]
titles = f()

One of my favorite features in Python :)

Longpoke
Suggest adding a link to the python docs: http://docs.python.org/tutorial/datastructures.html#list-comprehensions
Jack Kelly
+1  A: 

The expression f(X) for X in Y if EXP is a list comprehension It will give you either a generator (if it's inside ()) or a list (if it's inside []) containing the result of evaluating f(X) for each element of Y, by only if EXP is true for that X.

In your case it will return a list containing every element from titles if the element has some children.

The ending [:-1] means, everything from the list apart from the last element.

viraptor