Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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]
like image 935
Ayoub M. Avatar asked Sep 02 '26 11:09

Ayoub M.


2 Answers

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())

like image 66
pyfunc Avatar answered Sep 04 '26 01:09

pyfunc


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 :)