Home > python > Some list comprehensions examples

Some list comprehensions examples

Example #1:
Read all files from a directory and keep *.jpg only.

some_dir = '/opt/example'
images = [x for x in os.listdir(some_dir) if x.lower().endswith('jpg')]

We could use globbing too, this is just an example.

Example #2:
Strip whitespace characters from a list of words.

li = ['  apple ', '     banana  ', '  kiwi']
li = [e.strip() for e in li]


Categories: python Tags:
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: