fertholidays.blogg.se

Python list comprehension
Python list comprehension





python list comprehension

First, let’s define a function and then use it on the ‘digits’ list: def form(n):

#Python list comprehension how to

This example will show you how to use a custom function use it in each element of a list using list comprehension. I will import the math library and use the square root function in all the elements of the ‘digits’ list: import math We can use the in-built functions in a list comprehension. An implementation of the same code with list comprehension: In this example, we have a for loop and an if-else statement. In this example, I will multiply the even elements of the ‘digits’ list by three and I will multiply the odd elements with three and add 1 to it to make it even. Here is how to do the same thing in a list comprehension: Here, we had to use an extra ‘if statement’ to check if the digit is even. I will divide all the even numbers of the ‘digits’ list above and make a new list. Now the same thing using a list comprehension: Īs you can see instead of 4 lines of code I had to write just one simple line of code. I will do it using a regular for loop first and then using a list comprehension. Let’s make a new list that includes the square of each element of the digits list. Let’s start by creating a simple list of digits: digits =

python list comprehension

In this article, I wi ll explain list comprehension with a lot of examples starting from the simplest example and keep moving towards the more complex problems. I am assuming you already know python programming at list beginner level. Doing a list comprehension is a comparatively faster and shorter way of writing a ‘for loop’. Performing an action of each element of a list or string and generation of a new list is very easy, short, and compact using list comprehension. List comprehension is a concise way of writing a for loop on a list or a string.







Python list comprehension