diff --git a/basics/lists-and-tuples.md b/basics/lists-and-tuples.md index 77ea0ca..41f7ad9 100644 --- a/basics/lists-and-tuples.md +++ b/basics/lists-and-tuples.md @@ -141,6 +141,29 @@ We'll talk more about loops [in the next chapter](loops.md). >>> ``` +Another useful things about list is **comprehension**. +**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] +>>> numbers_squared = [ number ** 2 for number in numbers ] +>>> numbers_squared +[1, 4, 9, 16, 25] +>>> +``` + +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