DEV Community

Cover image for Python list comprehension
Max
Max

Posted on

Python list comprehension

Python list is used to store multiple value with different data types, values inside a list can be accessed or retrieved using index.

Create a new list with the addition of each number in an existing list

consider the following example if we want to do some operation the values inside the list we have to python for loop to iterate over each one.

l = [1,2,3,4,5]
m = []
for i in l:
    m.append(i+i)
print("m:", m) # Output: m: [2, 4, 6, 8, 10]
Enter fullscreen mode Exit fullscreen mode

Python have its own pythonic style of writing the code in a single line.

l = [1,2,3,4,5]
m = [i+i for i in l]
print("m:", m) # Output: m: [2, 4, 6, 8, 10]
Enter fullscreen mode Exit fullscreen mode

Creating a new list out of the first letter of every word in a string

myString = "Hello World Python Code"

myList = []
for s in myString.split(" "):
    myList.append(s[0])

print("myList:", myList) # Output: myList: ['H', 'W', 'P', 'C']
Enter fullscreen mode Exit fullscreen mode

Using list comprehension

myString = "Hello World Python Code"

myList = [s[0] for s in myString.split(" ")]

print("myList:", myList) # Output: m: [2, 4, 6, 8, 10]
Enter fullscreen mode Exit fullscreen mode

Explore Other Related Articles

How to combine two dictionaries in python using different methods
How to check if a key exists in a dictionary python
Python try exception tutorial
Python classes and objects tutorial
Python Recursion Function Tutorial
Python Lambda Function Tutorial

Top comments (1)

Collapse
 
eteimz profile image
Youdiowei Eteimorde

No matter how many times I use list comp it still feels magical.