Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chris Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

how to use list comprehension

Python Lists

how to use list comprehension

by  Bong  Posted    (Edited  )
I love Python's List Comprehension. It allows for very compact, yet readable, code. It is also useful for some pretty complex structures.

This is what it says in the Language Reference document:
When a list comprehension is supplied, it consists of a single expression followed by at least one for clause and zero or more for or if clauses. In this case, the elements of the new list are those that would be produced by considering each of the for or if clauses a block, nesting from left to right, and evaluating the expression to produce a list element each time the innermost block is reached.
Not what I'd call altogether useful.

Consider that you might want to take a long list of email addresses and extract only those addresses that share a domain (or possibly a few domains). That might be because you want to only respond to those in your own company or something like that. Anyway it's just an example.

So, you have a string:
Code:
s='abc@xyz.com,xyz@abc.com,aaa@abc.com,bbb@xyz.com,bbb@rts.com'
Make it a list:
Code:
d=s.split(',')

Now the pretty part. I only want those addresses with "abc.com":
Code:
d2=[b for b in d if b.endswith('abc.com')]
or I want to exclude all "abc.com":
Code:
d2=[b for b in d if not b.endswith('abc.com')]
obviously, or I want "abc.com" and "rts.com" but nothing else:
Code:
t=('abc.com','rts.com')
d2=[b for b in d if b.endswith(t)]
This is really not a feature of list comprehension but of endswith as it allows the argument to be a tuple.
Register to rate this FAQ  : BAD 1 2 3 4 5 6 7 8 9 10 GOOD
Please Note: 1 is Bad, 10 is Good :-)

Part and Inventory Search

Back
Top