DEV Community

Discussion on: Many Things You Can Do With Python Lists You May Have Missed

Collapse
 
waylonwalker profile image
Waylon Walker • Edited

Lol, good catch. 😳 I think I took a break between the comment and finding a good example. Here is a real example of nearly the same thing if the DataFrame was a pyspark DataFrame. pyspark.select takes in column names as *args df.select('us_price', 'eu_price')

They can be selected programatically with a list comprehension and *unpacking.

df_prices = df.select(*[col for col in df.columns if 'price' in col])
Thread Thread
 
aumayeung profile image
John Au-Yeung

I see. The list comprehension is used as a predicate?

Thread Thread
 
waylonwalker profile image
Waylon Walker • Edited

Not sure what you mean by predicate, the list comprehension is a filter.

price_cols = [col for col in df.columns if 'price' in col]
df_prices = df.select(*price_cols)

Here is a generally relatable example using the print statement

[ins] In [1]: fruits = ['apple', 'orange', 'orange', 'grape', 'pear']

[ins] In [2]: print(fruits)
['apple', 'orange', 'orange', 'grape', 'pear']

[ins] In [3]: print('apple', 'orange', 'orange', 'grape', 'pear')
apple orange orange grape pear

[ins] In [4]: print(*fruits)
apple orange orange grape pear

[ins] In [5]: print(*[fruit for fruit in fruits if 'p' in fruit])
apple grape pear
Thread Thread
 
aumayeung profile image
John Au-Yeung

That makes sense. I haven't seen this documented in many places. That's probably why I missed this.