List Comprehension in Python:
|We can use the PyCharm code editor for this example. If you do not know about it then follow this link- How to install PyCharm for Python and create a program in it.|
(1) List comprehension is an elegant way to define and create lists based on existing lists.
(2) List comprehension is generally more compact and faster than normal functions and loops for creating a list.
(3) Syntax of List Comprehension in Python:
|[expression for an item in list]|
(4) Example of List Comprehension:
- First, we take the case of a blank list.
- Now we take the case of the append() function. Appends a single element passed as an argument at the end of the list. The single element can also be a list.
- List comprehension uses a “for” loop.
- List comprehension uses “for” loop and “if“.