List comprehensions

List comprehension is a concise way of creating lists. In this section, we will use a list with the for loop. If you have not read about the for loop so far, you can skip this section and get back after learning about the for loop, covered in Chapter 6, Control Statements and Loops.

Let's take a list1 list as shown:

list1 = [2,3,4,5,6]

Now, our aim is to make a new list that contains the square of the elements of list1:

list1 = [2,3,4,5,6]

list2 = []

for each in list1:

list2.append(each*each)

print list2

The output of the program is as follows:

Square of list

The preceding code took four lines to create the desired list. By using list comprehensions, we can do the preceding stuff in just one line:

>>> list1 = [2, 3, 4, 5, 6]

>>> [each*each for each in list1]

[4, 9, 16, 25, 36]

>>>

Let's have a look at some more examples with the if statement.

 Create a new list that would contain the square of the even numbers of a given list:

list1 = [2,3,4,5,6]

list2 = []

for each in list1:

if each%2== 0:

list2.append(each*each)

print list2

The output of the preceding code snippet is as follows:

List with if statement

 Let's do it by using list comprehension:

>>> list1 = [2,3,4,5,6]

>>> [each*each for each in list1 if each%2 == 0]

[4, 16, 36]

>>>
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.14.144.216