Python list comprehensions

I don’t know if you have used list comprehension in Python. It is a great feature. You can go through a list and do some small changes with very little effort. Here is an example;

For example you have a list of user names and you would like to shorten these user names to 8 characters.

usernames = ['rtoodtoonet','cartmanmartman','kennymenny','southpark','kyle','brian']
short_username = [ user[:8] for user in usernames ]
print short_username

As you know you can iterate a python list with a construct like;

for user in usernames:

If you want to do some operations on this returned value (user), you can just put an expression in front of this for loop and remove the colon like;

user[:8] for user in usernames

The output from the code above will be ;

['rtoodtoo', 'cartmanm', 'kennymen', 'southpar', 'kyle', 'brian']

It looks fine. What about the user names laving less than 8 characters. Assume you want to fetch those which have at least 8 characters or more and ignore the others! It is also possible with a one liner. If you put an if condition right next to our for loop, magic happens;

short_username = [ user[:8] for user in usernames if len(user)>=8 ]

The new output will be like;

['rtoodtoo', 'cartmanm', 'kennymen', 'southpar']

To be honest, although list comprehension is quite nice, to me it looks a bit perlish way. Because when you look at the statement it looks like a complex one liner but if you can break it down to pieces like “operation : for expression : if statement” it is really easy!

About: rtoodtoo

Worked for more than 10 years as a Network/Support Engineer and also interested in Python, Linux, Security and SD-WAN // JNCIE-SEC #223 / RHCE / PCNSE


You have a feedback?

Discover more from RtoDto.net

Subscribe now to keep reading and get access to the full archive.

Continue reading