17
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])
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)
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])
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)
Output
['abc', 456, 3.14, 'mary']
Sets
set_a = {1,'efg',9.8}
list(set_a)
Output
[1, 'efg', 9.8]
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())
Output
['A', 'B']
[404, 911]
[('A', 404), ('B', 911)]
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]
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)
Output
[0,1,2,3,4]
To print a number of a certain type e.g ten zeros
[0 for i in range(10)]
Output
[0,0,0,0,0,0,0,0,0,0]
To print squares of numbers within a specified range
[i**2 for i in range(1,8)]
Output
[1,4,9,16,25,36,49]
To multiply elements of a list by a constant.
L = [2,4,9,4,61]
[i*10 for i in L]
Output
[20, 40, 90, 40, 610]
Duplicating string characters
string = 'Hello World'
[c*2 for c in string]
Output
['HH', 'ee', 'll', 'll', 'oo', ' ', 'WW', 'oo', 'rr', 'll', 'dd']
w = ['one', 'two', 'three', 'four', 'five', 'six']
[m[0] for m in w]
Output
['n', 'w', 'h', 'o', 'i', 'i']
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]
Output
[9, 61]
w = ['one', 'two', 'three', 'four', 'five', 'six']
[m[1] for m in w if len(m)==3]
Output
['n', 'w', 'i']
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.
17