PYTHON DATA SCIENCE TOOLBOX II, Schemes and Mind Maps of Web Programming and Technologies

Python Data Science Toolbox II. For loop and list comprehension syntax. In [1]: new_nums = [num + 1 for num in nums]. In [2]: for num in nums:.

Typology: Schemes and Mind Maps

2022/2023

Uploaded on 02/28/2023

arien
arien 🇺🇸

4.8

(24)

309 documents

1 / 29

Toggle sidebar

This page cannot be seen from the preview

Don't miss anything!

bg1
PYTHON DATA SCIENCE TOOLBOX II
List
comprehensions
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12
pf13
pf14
pf15
pf16
pf17
pf18
pf19
pf1a
pf1b
pf1c
pf1d

Partial preview of the text

Download PYTHON DATA SCIENCE TOOLBOX II and more Schemes and Mind Maps Web Programming and Technologies in PDF only on Docsity!

List

comprehensions

Populate a list with a for loop

In [1]: nums = [ 12 , 8 , 21 , 3 , 16 ] In [2]: new_nums = [] In [3]: for num in nums: ...: new_nums.append(num + 1 ) In [4]: print(new_nums) [13, 9, 22, 4, 17]

For loop and list comprehension syntax

In [1]: new_nums = [num + 1 for num in nums] In [2]: for num in nums: ...: new_nums.append(num + 1 ) In [3]: print(new_nums) [13, 9, 22, 4, 17]

List comprehension with range()

In [1]: result = [num for num in range( 11 )] In [2]: print(result) [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

Nested loops (1)

In [1]: pairs_1 = [] In [2]: for num1 in range( 0 , 2 ): ...: for num2 in range( 6 , 8 ): ...: pairs_1.append(num1, num2) In [3]: print(pairs_1) [(0, 6), (0, 7), (1, 6), (1, 7)]

● How to do this with a list comprehension?

Nested loops (2)

In [1]: pairs_2 = [(num1, num2) for num1 in range( 0 , 2 ) for num in range( 6 , 8 )] In [2]: print(pairs_2) [(0, 6), (0, 7), (1, 6), (1, 7)]

● Tradeoff: readability

Advanced

comprehensions

Conditionals in comprehensions

● Conditionals on the iterable

In [1]: [num ** 2 for num in range( 10 ) if num % 2 == 0 ] Out[1]: [0, 4, 16, 36, 64]

Python documentation on the % operator:

In [1]: 5 % 2 Out[1]: 1 In [2]: 6 % 2 Out[2]: 0

Dict comprehensions

● Create dictionaries

Use curly braces {} instead of brackets []

In [1]: pos_neg = {num: -num for num in range( 9 )} In [2]: print(pos_neg) {0: 0, 1: -1, 2: -2, 3: -3, 4: -4, 5: -5, 6: -6, 7: -7, 8: -8} In [3]: print(type(pos_neg)) <class 'dict'>

Let’s practice!

Generator expressions

● Recall list comprehension

In [1]: [ 2 * num for num in range( 10 )] Out[1]: [0, 2, 4, 6, 8, 10, 12, 14, 16, 18] In [2]: ( 2 * num for num in range( 10 )) Out[2]: <generator object at 0x1046bf888>

● Use ( ) instead of [ ]

List comprehensions vs. generators

● List comprehension - returns a list

● Generators - returns a generator object

● Both can be iterated over

Printing values from generators (2)

In [1]: result = (num for num in range( 6 )) In [2]: print(next(result)) 0 In [3]: print(next(result)) 1 In [4]: print(next(result)) 2 In [5]: print(next(result)) 3 In [6]: print(next(result)) 4

Lazy evaluation

Generators vs list comprehensions