Ali
Ali

Reputation: 13

Is it possible to write multiple statements in Python list comprehension?

I am trying to read an HTML table into pandas and then print and also append the DataFrames to a list as well. Something like:

dfs = pd.read_html(str(table))
[print(df),records_list.append(df), for df in dfs]

Upvotes: 1

Views: 606

Answers (2)

DocDriven
DocDriven

Reputation: 3974

It is possible, but its not really pretty:

inputs = ['a', 'b', 'c']

mylist = [print(i) or i for i in inputs]

print(mylist)

This abuses the fact that the print function returns None all the time. The result is:

a
b
c
['a', 'b', 'c']

That being said, I would NOT recommend to do this and rather go with @alexce's answer.

Upvotes: 3

alecxe
alecxe

Reputation: 474191

Not directly, you would either need to expand it to a regular loop:

for df in dfs:
    print(df)
    records_list.append(df)

Or, you could even create a custom function where you would print and return:

def print_and_return(item): 
    print(item)
    return item

records_list = [print_and_return(df) for df in dfs]

Upvotes: 2

Related Questions