An Introduction to Python Comprehensions
Comprehension can be done in the data structures of Python like lists, dictionaries, set, and generators. In Python, comprehension gives an accurate technique of writing a program. It reduces the size of the code without compromising its readability.
Python supports 4 types of comprehensions:
- List Comprehensions
- Dictionary Comprehensions
- Set Comprehensions
- Generator Comprehensions
All about List Comprehensions- Lists are enclosed in square brackets and it can hold values of multiple data types. List comprehension is a way of making list but in a single, short line. Yet, many developers struggle to fully understand list comprehension in Python and use for loops in so many places. That can lead to code that’s less efficient and difficult to read. If you find yourself using a for loop along with .append() to create a list, the list comprehension is a good substitute.
For example, you want to make a list using a for loop using letters from a string. The basic syntax is as follows:
Every list comprehension in Python includes three elements:
- The Expression : It is a call to a method or any other actual expression that returns a value.
- The member : is the object or value in the list or any iterable object.
- The iterable : is a list, set, sequence, generator, or any other object that can return its elements one at a time.