Getting Started With List Comprehension In Python 3.9.1.

Share on facebook
Share on google
Share on twitter
Share on linkedin
Cleaning up your Python code!

In programming languages, sequence awareness or list comprehension is a syntactic construct for noting a list. It is based on mathematical notation for collections.

A list extension is a syntactic sugar since the same can be accomplished with other language constructs, such as the higher-order map and filter functions. Some programming languages ​​in which sequence awareness can be used are Python and Haskell.

Let’s get started with our lists!


Creating a List

Let’s create a Python list that contains a string with each letter of that string as an element:

list = []
myString = "hello medium"
for x in myString:
list.append(x)
list

Which will result in:

$ py list_comp.py 
['h', 'e', 'l', 'l', 'o', ' ', 'm', 'e', 'd', 'i', 'u', 'm']

We can use Python functions to speed up the process of creating a list with a string:

def listMaker(string):
list = []
for x in string:
list.append(x)
return list
myList = listMaker("hello medium")
print(myList)

Which gives me the same output:

$ py list_comp.py 
['h', 'e', 'l', 'l', 'o', ' ', 'm', 'e', 'd', 'i', 'u', 'm']

Creating a list using List comprehension

Even though this works, we want to use a much faster way to execute and write for clean code purposes.

The following code will create the same function:

def compListMaker(string):
return [x for x in string]

Full code:

def compListMaker(string):
return [x for x in string]
myList = compListMaker("hello medium")
print(myList)

With result:

$ py list_comp.py
['h', 'e', 'l', 'l', 'o', ' ', 'm', 'e', 'd', 'i', 'u', 'm']

Another Example

Let’s create another example, this time with a calculation. Case: we have a list with numbers (1,2,3,4,5), and we want to create a function that multiplies it with the number you enter:

def compListMaker2(x, list):
return [y * x for y in list]

This will solve our problem, as you can see by multiplying each element in the list(y) with the x that you have given as an argument:

def compListMaker2(x, list):
return [y * x for y in list]
list = [1, 2, 3, 4, 5]
myList2 = compListMaker2(2, list)
print(myList2)

Result:

$ py list_comp.py
[2, 4, 6, 8, 10]
bryan@dijkhuizenmedia.com

bryan@dijkhuizenmedia.com

Leave a Replay

Sign up for our Newsletter

Click edit button to change this text. Lorem ipsum dolor sit amet, consectetur adipiscing elit