From 8b04830b561e65b1a0f63b4201f42a526269d665 Mon Sep 17 00:00:00 2001 From: Luc Street Date: Wed, 2 Oct 2019 14:55:26 -0700 Subject: [PATCH] Add python list comprehension sheet --- sheets/_python/list_comprehension | 12 ++++++++++++ 1 file changed, 12 insertions(+) create mode 100644 sheets/_python/list_comprehension diff --git a/sheets/_python/list_comprehension b/sheets/_python/list_comprehension new file mode 100644 index 0000000..5647a22 --- /dev/null +++ b/sheets/_python/list_comprehension @@ -0,0 +1,12 @@ +# List comprehensions are a compact way to define a list +squares = [x**2 for x in range(1, 10)] +# squares = [1, 4, 9, 16, 25, 36, 49, 64, 81, 100] + +# You can also add a condition to filter out some of the elements +evens = [i for i in range(1, 10) if i % 2 == 0] +# evens = [2, 4, 6, 8] + +# If your list is multi-dimensional, you can nest for-loops +matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] +flattened = [val for row in matrix for val in row] +# flattened = [1, 2, 3, 4, 5, 6, 7, 8, 9]