List Comprehensions vs For Loop
There are various ways to iterate through a list. However, the most common approach is to use the for loop. Let us look at the below example:
Python
# Empty list List = [] # Traditional approach of iterating for character in 'Geeks 4 Geeks!' : List .append(character) # Display list print ( List ) |
Output
['G', 'e', 'e', 'k', 's', ' ', '4', ' ', 'G', 'e', 'e', 'k', 's', '!']
Above is the implementation of the traditional approach to iterate through a list, string, tuple, etc. Now, list comprehension in Python does the same task and also makes the program more simple.
List Comprehensions translate the traditional iteration approach using for loop into a simple formula hence making them easy to use. Below is the approach to iterate through a list, string, tuple, etc. using list comprehension in Python.
Python
# Using list comprehension to iterate through loop List = [character for character in 'Geeks 4 Geeks!' ] # Displaying list print ( List ) |
Output
['G', 'e', 'e', 'k', 's', ' ', '4', ' ', 'G', 'e', 'e', 'k', 's', '!']
Python – List Comprehension
A Python list comprehension consists of brackets containing the expression, which is executed for each element along with the for loop to iterate over each element in the Python list.
Example:
Python
numbers = [ 12 , 13 , 14 ,] doubled = [x * 2 for x in numbers] print (doubled) |
Output
[24, 26, 28]