From 6f3429e5ba5b9fe3801dba1f7f44dc0410baff27 Mon Sep 17 00:00:00 2001 From: Varian Caesar Date: Sun, 13 Oct 2019 00:37:53 +0700 Subject: [PATCH 1/2] feat: Add list comprehension in list tutorial --- basics/lists-and-tuples.md | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/basics/lists-and-tuples.md b/basics/lists-and-tuples.md index 77ea0ca..2bb4dff 100644 --- a/basics/lists-and-tuples.md +++ b/basics/lists-and-tuples.md @@ -141,6 +141,17 @@ We'll talk more about loops [in the next chapter](loops.md). >>> ``` +Another useful things about list is **comprehension**. +**Comprehension** is a way to loop the list in single line. It makes our code more pythonic. + +```python +>>> numbers = [1,2,3,4,5] +>>> numbers_squared = [ number ** 2 for number in numbers ] +>>> numbers_squared +[1, 4, 9, 16, 25] +>>> +``` + We can also use slicing and indexing to change the content: ```python From bff51ee93b8c2c9fce4b85d1aad372aaf1fa43fb Mon Sep 17 00:00:00 2001 From: Varian Caesar Date: Mon, 21 Oct 2019 00:50:06 +0700 Subject: [PATCH 2/2] Add example with vs without list comprehension --- basics/lists-and-tuples.md | 14 +++++++++++++- 1 file changed, 13 insertions(+), 1 deletion(-) diff --git a/basics/lists-and-tuples.md b/basics/lists-and-tuples.md index 2bb4dff..41f7ad9 100644 --- a/basics/lists-and-tuples.md +++ b/basics/lists-and-tuples.md @@ -142,7 +142,7 @@ We'll talk more about loops [in the next chapter](loops.md). ``` Another useful things about list is **comprehension**. -**Comprehension** is a way to loop the list in single line. It makes our code more pythonic. +**Comprehension** is a way to construct a list in single line. It makes our code more clean, shorter and easier to read. ```python >>> numbers = [1,2,3,4,5] @@ -152,6 +152,18 @@ Another useful things about list is **comprehension**. >>> ``` +without comprehension: + +```python +>>> numbers = [1,2,3,4,5] +>>> numbers_squared = [] +>>> for number in numbers: +... numbers_squared.append(number**2) +>>> numbers_squared +[1, 4, 9, 16, 25] +>>> +``` + We can also use slicing and indexing to change the content: ```python pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy