Lists in Python are one of the four built-in structures in Python. Other data structures that you may know are tuples, dictionaries, and sets. A list in Python is unique in relation to, for instance, int or bool, as in it’s a compound data type: you can group values in lists. These values don’t need to be of a similar sort: they can be a mix of boolean, String, integer, float values.
List literals are a collection of data surrounded by brackets, and the elements are separated by a comma. The list is fit for holding different data types inside it, in contrast to arrays.
For instance, suppose you need to build a list of courses then you could have:
pets = ['dogs','cats','birds']
Python list comprehension
List comprehension in Python is additionally encircled by brackets, however rather than the list of data inside it, you enter an expression followed by for loop and if-else clauses.
A most fundamental type of List comprehension in Python is developed as follows: list_variable = [expression for an item in the collection] The first expression produces elements in the list followed by a for loop over some collection of data which would assess the expression for each item in the collection.
Let’s see how the syntax works:
new_list = [x for x in some_iterable]
Here you can see that list comprehension is determined by square brackets (simply like the list itself) inside which you have a for loop over some iterable object. In our model, the new list will basically comprise of all elements from some_iterable object. The code above is totally identical to the one beneath, nonetheless, it takes less space and works somewhat quicker!
new_list =  for x in some_iterable: new_list.append(x)
You may wonder why there is a requirement for list comprehensions at all since we have a list() function. Clearly, list comprehensions are utilized not only for replicating elements from some iterable into a list, yet mainly for modifying them someway to make a particular new list. For this situation, in any case of the list comprehension, we write some function of our variable. For instance, the code beneath tells the best way to make a list of squared numbers
numb = [10, 20, 30] square_list = [x * x for x in numb] print(square_list)
Also, we can use list comprehensions to convert elements of a list from one data type to another:
strings = ["8.9", "6.0", "8.1", "7.5"] floats = [float(num) for num in strings] print(floats)
List comprehension vs. for loop in Python
As you would know, you use for loops to repeat a block of code a fixed number of times. List Comprehensions are acceptable options to for loops, as they are increasingly reduced. Consider the accompanying model that begins with the variable numbers, defined as a range from 0 up until 9.
Remember that the number that you pass to the range() function is the number of integers that you need to create, beginning from zero, obviously. This implies range(10) will return [0,1,2,3,4,5,6,7,8,9].
If you now want to operate on every element in numbers, you can do this with a for loop, just like the one below:
numbers = range(10) new_list =  for n in numbers: if n%2==0: new_list.append(n**2) print(new_list)
This is all nice and well, but now consider the following example of a list comprehension, where you do the same with a more compact notation:
new_list = [n**2 for n in numbers if n%2==0] print(new_list)
Filter and Lambda functions in the list comprehension
To convert the map() function in combination with a lambda function, you can likewise handle code that contains the Python filter() function with lambda functions and revise that too.
In the accompanying model, you will filter through even numbers and just keep the odd numbers:
kilometer = [39.2, 36.5, 37.3, 37.8] feet = [float(3280.8399)*x for x in kilometer] #coverting feet to kilometer feet = list(map(int, feet)) uneven = filter(lambda x: x%2, feet) type(uneven) print(list(uneven))
To revise the lines of code in the above model, you can utilize two list comprehensions:
- One to convert the values of feet to integers;
- Second to filter out even values from the feet list.
To begin with, you rewrite the map() function, which you use to convert the elements of the feet list to whole numbers. At that point, you tackle the filter() function: you take the body of the lambda function, utilize the for and in keywords to legitimately associate x and feet:
feet = [int(x) for x in feet] print(feet) uneven = [x for x in feet if x%2!= 0] print(uneven)
List comprehension with if
Another way to modify the original iterable object is by introducing the if statement into the list comprehension. The basic syntax is this:
new_list = [x for x in some_iterable if condition]
The conditional statement permits you to filter the elements of the original collection and work just with the elements you need. The if statement works here as a part of a comprehension syntax. The filtering condition isn’t a mandatory part, yet it tends to be extremely valuable. For example, here it is utilized to create a list of odd numbers from another list:
numb = [124, 67, 15, 106, 26, 42, 10] odd = [x for x in numb if x % 2 == 1] print(odd)
You can also modify the condition by using standard methods. For instance, if you want to create a list of words that end in -tion, you can do it like this:
text = ["function", "is", "a", "synonym", "of", "occupation"] words_tion = [word for word in text if word.endswith("tion")] print(words_tion)
Finally, we can introduce the else statement in list comprehension. The syntax here differs a bit: [x if condition else y for x in some_iterable]. Using this, we can, for example, get 0 in a new list for each negative number in the old list:
list1 = [80, 3, -27, 56, -9, 12, 10] new_list = [num if num >= 0 else 0 for num in list1] print(new_list)
Multiple if conditions
Since you have seen how you can include conditions, it’s an ideal opportunity to convert the accompanying for loop to a list comprehensions with conditionals.
div =  for x in range(100): if x%2 == 0 : if x%6 == 0: div.append(x)
Be cautious, you see that the accompanying for loop contains two conditions! To comprehend this, you should simply include two if conditions one followed by another. Just when the two conditions are fulfilled, the expression will be added to the list. In the accompanying example, the expression x will be included as a multiple of 6.
div = [x for x in range(100) if x % 2 == 0 if x % 6 == 0] print(div)
Nested list comprehension
Aside from conditionals, you can likewise alter your list comprehensions by nesting them inside other list comprehensions. This is convenient when you need to work with list of lists: producing list of lists, transposing list of lists, or flattening list of lists to standard list. For instance, it turns out to be incredibly simple with nested list comprehensions.
list1 = [[1,2,3],[4,5,6],[7,8]] [y for x in list1 for y in x]
You see that the majority of the keywords and elemnets utilized in the case of the nested list comprehension are like those you utilized in the basic list comprehension examples:
- Square brackets
- Two for keywords, followed by a variable that represents an item of the list of lists (x) and a list item of a nested list (y)
- Two in keywords, followed by a list of lists (list1) and a list item (x).
Let’s now consider another example, where you see that you can also use two pairs of square brackets to change the logic of your nested list comprehension:
matrix = [[10,20,30],[40,50,60],[70,80,90]] [[row[i] for row in matrix] for i in range(3)]
- List comprehension is an elegant way to characterize and create lists dependent on existing lists.
- List comprehension is commonly more compact and quicker than typical functions and loops for making list.
- Although, we should avoid writing long extensive list comprehensions in a single line to guarantee that code is easy to use.
- Keep in mind, each list comprehension can be reworked in for loop, however, every for loop can’t be rewritten as list comprehension.
Let’s try to solve the problem:
Write a program that divides numbers into two lists depending on whether they are greater than or less than 5. You don’t have to include number 5 itself.
A sequence of numbers has been read from the input for you.
Sample Input 1:
Sample Output 1:
numbers = [int(n) for n in input()] less_than_5 = [x for x in numbers if x < 5] greater_than_5 = [x for x in numbers if x > 5] print(less_than_5) print(greater_than_5)