![]() |
|
[Tut] Python Function Call Inside List Comprehension - Printable Version +- Sick Gaming (https://sickgaming.net) +-- Forum: Programming (https://sickgaming.net/forum-76.html) +--- Forum: Python (https://sickgaming.net/forum-83.html) +--- Thread: [Tut] Python Function Call Inside List Comprehension (/thread-98288.html) |
[Tut] Python Function Call Inside List Comprehension - xSicKxBot - 11-15-2020 Python Function Call Inside List Comprehension Question: Is it possible to call a function inside a list comprehension statement? Background: List comprehension is a compact way of creating lists. The simple formula is Code: [expression + context]
For example, the code Code: [x**2 for x in range(3)]Code: [0, 1, 4]Code: x**2Related article: List Comprehension in Python — A Helpful Illustrated Guide So, can you use a function with or without return value as an expression inside a list comprehension? Answer: You can use any expression inside the list comprehension, including functions and methods. An expression can be an integer Code: 42Code: 2+2 (=4)Code: np.sum(x)Code: xCode: NoneHere’s an example: Code: [print('hi') for _ in range(10)] '''
hi
hi
hi
hi
hi
hi
hi
hi
hi
hi '''You use the throw-away underscore Code: _Code: [print(i) for i in range(10)] '''
0
1
2
3
4
5
6
7
8
9 '''Let’s have a look at the content of the list you just created: Code: lst = [print(i) for i in range(10)]
print(lst)
# [None, None, None, None, None, None, None, None, None, None]The list contains ten Code: NoneCode: print()Code: NoneWalrus Operator Python 3.8 has introduced the walrus operator, also known as the assignment expression. This operator is useful if executing a certain function has side effects that you don’t want. For example, if you have a string creation method inside the list comprehension statement, conditioned by some filtering criterion in the if suffix. Without the walrus operator, Python would execute this same routine multiple times—even though this is highly redundant. You can avoid this redundancy by assigning it to a variable Code: sCode: import random def get_random_string(): return f'sss {random.randrange(0, 100)}' # Goal: Print all random strings that contain 42 # WRONG
lst = [get_random_string() for _ in range(1000) if '42' in get_random_string()]
print(lst)
# ['sss 74', 'sss 13', 'sss 76', 'sss 13', 'sss 92', 'sss 96', 'sss 27', 'sss 43', 'sss 80'] # CORRECT
lst = [s for _ in range(1000) if '42' in (s := get_random_string())]
print(lst)
# ['sss 42', 'sss 42', 'sss 42', 'sss 42', 'sss 42', 'sss 42', 'sss 42', 'sss 42', 'sss 42', 'sss 42', 'sss 42', 'sss 42', 'sss 42']With the walrus operator Code: s := get_random_string()Code: sI teach these concepts in my exclusive FINXTER email academy—join us, it’s free! Related Video: List Comprehension The post Python Function Call Inside List Comprehension first appeared on Finxter. |