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.

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

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;

The output from the code above will be ;

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;

The new output will be like;

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!

You have a feedback?