List Comprehensions in Python

Using a for loop, we code:Using list_comprehension, this becomes:The beauty of list_comprehension becomes more apparent when we start considering nested for loops.Consider a program to find the Cartesian product of two lists.Now using list comprehension:A final example would be to find common numbers between two lists using list comprehension:Key TakeawaysList comprehension provides an elegant way of defining lists based on other existing lists.It is generally more compact and faster as it is optimized for the Python interpreter.If you have several nested loops, it might be a good idea to avoid writing down a very long list comprehension and stick to the normal loop syntax in favor of readability.. More details

Leave a Reply