List comprehension in Python | Laptrinhcanban.com

HOME › >>

List comprehension in Python

Posted at: https://laptrinhcanban.com/en

Let’s learn about List comprehension in Python as well as how to create List comprehension in this lesson.

What are List comprehension in Python

When working with lists, there will be times when you will need to manipulate complex structured lists, for which with the usual list creation method, you will need a lot of code to be able to initialize them.
But the founders of python with the belief that simple python is better than complex , created list comprehension - a special method that only python has, in order to help you shorten essential lines of code and create a complex list in the blink of an eye.
In addition to the ability to shorten the lines of code to write, the processing speed of list comprehension method in Python is also considered to be faster than other methods.

Create lists by list comprehension in Python

To create list comprehension in Python , we use the following syntax:

[expression for variable in iterable]

Inside:

  • expression : A calculated expression that creates the element of a new list.
  • variable : variable is created to assign values ​​of elements within iterable. Through biến, these values ​​will be used to compute biểu thứcand create a new list element.

You can use functions such as a built-in python upper, lower, absetc. Or you can write the function yourself and use it biểu thứcabove.

About the processing process as follows:

1. Create a loop with the for function . 
2. In each iteration, the value of each element in the initial list is assigned to the variable
3. Pass the variable into the expression and compute the expression for a result.
4. Use this result as an element to create a new list .

Let’s see some practical examples as follows:

Create a list of numbers 1 through 5

comprehension_list = [number for number in range(0,6)]

print(comprehension_list)
#>>[0, 1, 2, 3, 4, 5]

Here we have used the range () function to create a list of numbers from 0 to 5, then take each value of the element in this list and assign it to the variable number, finally used numberto create the list comprehension_list.
You can see more about how to create a new list using the range function in the article Create list by an iterable in python

If we do not have list comprehension , we must write the following code:

old_list = list(range(0,6))
comprehension_list = []

for phantu in old_list:
comprehension_list.append(phantu)

print(comprehension_list)
#>>[0, 1, 2, 3, 4, 5]

You see, the same results, but using list comprehension has helped us to reduce the code, reducing the effort.

Create a list whose element is the square of numbers from 1 to 5
This example is a bit more complicated, we do not simply use the element value of the old list, but we need to square this value, then square it. create a new list.

comprehension_list = [number**2 for number in range(0,6)]

print(comprehension_list)
#>> [0, 1, 4, 9, 16, 25]

And the traditional way of writing would be:

old_list = list(range(0,6))
comprehension_list = []

for phantu in old_list:
phantu_moi = phantu**2
comprehension_list.append(phantu_moi)

print(comprehension_list)
#>> [0, 1, 4, 9, 16, 25]

Given a list of different strings, create a new list with the strings in LOWER format.

list_thanhpho = ['Long An', 'Ha Noi','Nam Dinh']
list_thanhpho_thuong = [thanhpho.lower() for thanhpho in list_thanhpho]

print(list_thanhpho_thuong)
#>>

You can see that with normal writing, the more complex the expression, the more lines we need to code.
But with list comprehension , you only need one line of code to solve the problem.
IT’S SO COOL

Manually create functions and create lists by List comprehension in Python

In the above section, we used expressions created by functions available in python such as lower, upper etc … You can also create the function yourself and use it instead of the existing functions, like in the the following example:

Given a list of integers. Create a new number list whose elements are powers of the numbers in the old list

list_number = list ( range ( 11 ))

def tim_luy_thua ( number ):
return number ** 2


new_list = [tim_luy_thua (number) for printed number list_those]
print (new_list)

Result

[0, 1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

For the list of animal names, create a new list of four-legged animals.

list_animal =[ 'dog' , 'cat' , 'snake' , 'elephant' , 'fish' ]

def find_four_leg (animal):
if animal in [ 'dog' , 'cat' , 'elephant' ]:
return animal

four_leg = [animal for animal in list_animal if find_four_leg(animal)]
print(four_leg)

Kết quả

['dog', 'cat', 'elephant']

Here you need to know more new knowledge such as:

  • def used to create a function
  • return is used to return the processing results of the function
  • in Used to check whether an element is in the list or not

On how to create new functions yourself in python , Kiyoshi would like to see you in a column for details later.

Use list comprehension in Python with IF function

We can also use the constructive method with the conditional function IF. Now, only when the conditional expression is true will the element be added to the new list. The written syntax will look like this:

[expression for variable in iterable if conditional expression]

About the processing process as follows:

1. Use the for function to get each element in the list and assign it to variable 
2. Use an expression to create a new value from the variable
3. Evaluate the conditional expression as TRUE or FALSE
4. If TRUE, use the result. formula as an element to create a new list

Let’s see the following specific example:

Creates a new list of even numbers from an original list of numbers

list_so = [0,1,2,3,4,5,6,7,8]
list_so_chan = [so for so in list_so if so%2 ==0]

print(list_so_chan)
#>> [0, 2, 4, 6, 8]

You can combine list creation using the range function and write the above extremely short example like so:

list_so_chan = [so for so in list(range(9)) if so % 2 ==0]

print(list_so_chan)
#>> [0, 2, 4, 6, 8]

If there is no method of writing the content, you will have to write lengthy code like the communication method below:

list_so = list(range(9))
list_so_chan = []

for so in list_so:
if so % 2 == 0:
list_so_chan.append(so)

print(list_so_chan)
#>> [0, 2, 4, 6, 8]

Once again, you can see that the list comprehension in Python can reduce your code and reduce your work a lot, right?

Summarize

List comprehension in Python is a special way of writing python, so if you are new to this, it can be confusing. But once you get used to it, Kiyoshi makes sure you get addicted to it and no longer want to write in the popular way.
With the advantages of processing power as well as the ability to shorten code, you will have a chance to encounter this writing in python projects. So hundred or not by hand, let’s master List comprehension in Python by re-practicing today’s examples.

And let’s learn more about Python in the next lessons.

URL Link

https://laptrinhcanban.com/en/python/nhap-mon-lap-trinh-python/list-trong-python/tao-list-bang-phuong-phap-viet-noi-ham-list-comprehension/

Thank you for reading and please Like & Share for other friends to learn.
">

HOME  › >>

  • Recent Posts
Profile
きよしです!笑

Author: Kiyoshi (Chis Thanh)

Kiyoshi was a former international student in Japan. After graduating from Toyama University in 2017, Kiyoshi is currently working at BrSE in Tokyo, Japan. Kiyoshi là một cựu du học sinh tại Nhật Bản. Sau khi tốt nghiệp đại học Toyama năm 2017, Kiyoshi hiện đang làm BrSE tại Tokyo, Nhật Bản.