Python Tutorial
[ expression for item in list if conditional ]
lists = [val*2 for val in range(6)] print lists;Output:
[0, 2, 4, 6, 8, 10]Suppose we need create above list without list comprehensions,
lists = [] for val in range(10): lists.append(val*2) print lists;
lists = [val*3 for val in range(10) if val%2 == 0] print lists;Output:
[0, 6, 12, 18, 24]
*new_list* = [*transform* *iteration* *filter*]
numbers = [' one', ' two ', 'three '] new_list = [number.strip() for number in numbers] print new_list;Output:
$ python list-coprehension.py ['one', 'two', 'three']
numbers = ['one', 'two', 'three'] new_list = [(number[0].upper() + number[1:]) for number in numbers] print new_list;Output:
$ python list-coprehension.py ['One', 'Two', 'Three']
string = "test 2345 numbers 322 43!"; new_list = [num for num in string if num.isdigit()] print new_list;Output:
$ python list-coprehension.py ['2', '3', '4', '5', '3', '2', '2', '4', '3']
string = "test 2345 numbers 322 43!"; new_list = [ch for ch in string if ch.isalpha()] print new_list;Output:
$ python list-coprehension.py ['t', 'e', 's', 't', 'n', 'u', 'm', 'b', 'e', 'r', 's']
string = "Test 2345 Numbers 322 43!"; new_list = [ch for ch in string if ch.islower()] print new_list;Output:
$ python list-coprehension.py ['e', 's', 't', 'u', 'm', 'b', 'e', 'r', 's']
new_list = [num, num**3 for num in range(1, 10)] print new_list;Interpreter error is generated because tuple values should be placed using parantheses'(' and ')'.
$ python list-coprehension.py File "list-coprehension.py", line 1 new_list = [num, num**3 for num in range(1, 10)] ^ SyntaxError: invalid syntaxCorrect way
new_list = [(num, num**3) for num in range(1, 10)] print new_list;Output:
$ python list-coprehension.py [(1, 1), (2, 8), (3, 27), (4, 64), (5, 125), (6, 216), (7, 343), (8, 512), (9, 729)]
new_list = [[num, num**2, num**3] for num in range(1, 10)] print new_list;Output:
$ python list-coprehension.py [[1, 1, 1], [2, 4, 8], [3, 9, 27], [4, 16, 64], [5, 25, 125], [6, 36, 216], [7, 49, 343], [8, 64, 512], [9, 81, 729]]
from math import pi new_list = [str(round(pi, i)) for i in range(5)] print new_list;Output:
$ python list-coprehension.py ['3.0', '3.1', '3.14', '3.142', '3.1416']
marks = [[67,87,54], [98, 56, 78, 86], [56, 89]]; new_list = [[round(float(sum(mark))/len(mark), i) for i in range(1,4)] for mark in marks] print new_list;Output:
$ python list-coprehension.py [[69.3, 69.33, 69.333], [79.5, 79.5, 79.5], [72.5, 72.5, 72.5]]
no_primes = [no_prime for div in range(2, 8) for no_prime in range(div*2, 100, div)] primes = [num for num in range(2, 100) if num not in no_primes] print primes;Output:
$ python list-coprehension.py [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97]« Previous Next »
Python Tutorial
Privacy Policy | Copyright2020 - All Rights Reserved. | Contact us
| Report website issues in Github
| Facebook page
| Google+ page