DEV Community

Cover image for Python List Comprehensions
Naftal Rainer
Naftal Rainer

Posted on

Python List Comprehensions

Hello readers, welcome to python article which involves handling python list comprehensions.
A list is a python data type that contains mutable elements enclosed within square brackets.
The elements contained may be of different data types or even other lists.

L = [123,'abc',[99,100],1.38]
Print(L[2][1])
Enter fullscreen mode Exit fullscreen mode

Why are list comprehensions preferred?

  • List comprehensions can be used for mapping and filtering hence eliminating the need to use a different approach for each scenario.
  • They can be used to rewrite loops and map() calls.

Built-in List Functions

  • len – Returns the number of items in the list.
  • sum - Returns the sum of items in the list.
  • min - Returns the minimum of items in the list.
  • max - Returns the maximum of items in the list.
  • append – appends a passed object into an existing list.
  • Count - Returns the number of times an object/item appears in a list.
  • extends - appends the sequence contents to the list.

For example

Average = sum(L)/len(L)
Enter fullscreen mode Exit fullscreen mode

Creating Lists

Apart from the explicit declaration of lists just like in the first example above, we can input a list using the keyboard or accept it as a piped input from another program.

List_1 = eval(input(Enter a list))
Print(The first element is : , L[0])
Enter fullscreen mode Exit fullscreen mode

We can as well obtain lists through conversion of other data types as shown below;

Tuples

tuple_a =('abc',456,3.14,'mary')
list(tuple_a)
Enter fullscreen mode Exit fullscreen mode

Output

['abc', 456, 3.14, 'mary'] 
Enter fullscreen mode Exit fullscreen mode

Sets

set_a = {1,'efg',9.8}
list(set_a) 
Enter fullscreen mode Exit fullscreen mode

Output

[1, 'efg', 9.8]
Enter fullscreen mode Exit fullscreen mode

Dictionaries
For a dictionary we can get the key, value and items separately

# Create the dictionary d
d = {'A':404, 'B':911}

# Generates the keys of d
list(d)

# Generate values
list(d.values())

# Generate items – key – value pairs
list(d.items())  
Enter fullscreen mode Exit fullscreen mode

Output

['A', 'B']
[404, 911]
[('A', 404), ('B', 911)]
Enter fullscreen mode Exit fullscreen mode

Comprehensions
Using list comprehensions is a faster and a very powerful way to create lists with predefined conditions.
Declaration is done using square brackets but in this case, instead of assigning intrinsic values, a condition is given to produce a matching output just like the set builder notation in mathematics.

syntax

newlist = [expression for item in iterable if condition == True]
Enter fullscreen mode Exit fullscreen mode

The condition only accepts the items that valuate to True.
The condition is however optional and can be omitted.
A few examples are as shown;

L = [i for i in range(5)]
Print(L)
Enter fullscreen mode Exit fullscreen mode

Output

[0,1,2,3,4]
Enter fullscreen mode Exit fullscreen mode

To print a number of a certain type e.g ten zeros

[0 for i in range(10)] 
Enter fullscreen mode Exit fullscreen mode

Output

[0,0,0,0,0,0,0,0,0,0]
Enter fullscreen mode Exit fullscreen mode

To print squares of numbers within a specified range

[i**2 for i in range(1,8)] 
Enter fullscreen mode Exit fullscreen mode

Output

[1,4,9,16,25,36,49]
Enter fullscreen mode Exit fullscreen mode

To multiply elements of a list by a constant.

L = [2,4,9,4,61] 
[i*10 for i in L]
Enter fullscreen mode Exit fullscreen mode

Output

 [20, 40, 90, 40, 610]
Enter fullscreen mode Exit fullscreen mode

Duplicating string characters

string = 'Hello World' 
 [c*2 for c in string]
Enter fullscreen mode Exit fullscreen mode

Output

['HH', 'ee', 'll', 'll', 'oo', '  ', 'WW', 'oo', 'rr', 'll', 'dd']
Enter fullscreen mode Exit fullscreen mode
w = ['one', 'two', 'three', 'four', 'five', 'six']
[m[0] for m in w] 
Enter fullscreen mode Exit fullscreen mode

Output

['n', 'w', 'h', 'o', 'i', 'i'] 
Enter fullscreen mode Exit fullscreen mode

You can also use control structures within a list comprehension to save time and efficiency of program as shown;

L = [2,4,9,4,61]
[i for i in L if i>5]
Enter fullscreen mode Exit fullscreen mode

Output

[9, 61]
Enter fullscreen mode Exit fullscreen mode
w = ['one', 'two', 'three', 'four', 'five', 'six']
[m[1] for m in w if len(m)==3]
Enter fullscreen mode Exit fullscreen mode

Output

['n', 'w', 'i']
Enter fullscreen mode Exit fullscreen mode

To conclude:
List comprehensions can accomplish complex tasks without using an overly complicated code and the good part is that you can do all that in one line.

Top comments (0)