SlideShare a Scribd company logo
1 of 30
Download to read offline
List comprehensions
P YTH ON DATA S CIEN CE TOOLBOX (PART 2)
Hugo Bowne-Anderson
Data Scientist at DataCamp
PYTHON DATA SCIENCE TOOLBOX (PART 2)
Populate a list with a for loop
nums = [12, 8, 21, 3, 16]
new_nums = []
for num in nums:
new_nums.append(num + 1)
print(new_nums)
[13, 9, 22, 4, 17]
PYTHON DATA SCIENCE TOOLBOX (PART 2)
A list comprehension
nums = [12, 8, 21, 3, 16]
new_nums = [num + 1 for num in nums]
print(new_nums)
[13, 9, 22, 4, 17]
PYTHON DATA SCIENCE TOOLBOX (PART 2)
For loop and list comprehension syntax
new_nums = [num + 1 for num in nums]
for num in nums:
new_nums.append(num + 1)
print(new_nums)
[13, 9, 22, 4, 17]
PYTHON DATA SCIENCE TOOLBOX (PART 2)
List comprehension with range()
result = [num for num in range(11)]
print(result)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
PYTHON DATA SCIENCE TOOLBOX (PART 2)
List comprehensions
Collapse for loops for building lists into a single line
Components
Iterable
Iterator variable (represent members of iterable)
Output expression
PYTHON DATA SCIENCE TOOLBOX (PART 2)
Nested loops (1)
pairs_1 = []
for num1 in range(0, 2):
for num2 in range(6, 8):
pairs_1.append(num1, num2)
print(pairs_1)
[(0, 6), (0, 7), (1, 6), (1, 7)]
How to do this with a list comprehension?
PYTHON DATA SCIENCE TOOLBOX (PART 2)
Nested loops (2)
pairs_2 = [(num1, num2) for num1 in range(0, 2) for num2 in range(6,
print(pairs_2)
[(0, 6), (0, 7), (1, 6), (1, 7)]
Tradeoff: readability
Let's practice!
P YTH ON DATA S CIEN CE TOOLBOX (PART 2)
Advanced
comprehensions
P YTH ON DATA S CIEN CE TOOLBOX (PART 2)
Hugo Bowne-Anderson
Data Scientist at DataCamp
PYTHON DATA SCIENCE TOOLBOX (PART 2)
Conditionals in comprehensions
Conditionals on the iterable
[num ** 2 for num in range(10) if num % 2 == 0]
[0, 4, 16, 36, 64]
Python documentation on the % operator: The % (modulo)
operator yields the remainder from the division of the rst
argument by the second.
5 % 2
1
6 % 2
0
PYTHON DATA SCIENCE TOOLBOX (PART 2)
Conditionals in comprehensions
Conditionals on the output expression
[num ** 2 if num % 2 == 0 else 0 for num in range(10)]
[0, 0, 4, 0, 16, 0, 36, 0, 64, 0]
PYTHON DATA SCIENCE TOOLBOX (PART 2)
Dict comprehensions
Create dictionaries
Use curly braces {} instead of brackets []
pos_neg = {num: -num for num in range(9)}
print(pos_neg)
{0: 0, 1: -1, 2: -2, 3: -3, 4: -4, 5: -5, 6: -6, 7: -7, 8: -8}
print(type(pos_neg))
<class 'dict'>
Let's practice!
P YTH ON DATA S CIEN CE TOOLBOX (PART 2)
Introduction to
generator
expressions
P YTH ON DATA S CIEN CE TOOLBOX (PART 2)
Hugo Bowne-Anderson
Data Scientist at DataCamp
PYTHON DATA SCIENCE TOOLBOX (PART 2)
Generator expressions
Recall list comprehension
[2 * num for num in range(10)]
[0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
Use ( ) instead of [ ]
(2 * num for num in range(10))
<generator object <genexpr> at 0x1046bf888>
PYTHON DATA SCIENCE TOOLBOX (PART 2)
List comprehensions vs. generators
List comprehension - returns a list
Generators - returns a generator object
Both can be iterated over
PYTHON DATA SCIENCE TOOLBOX (PART 2)
Printing values from generators (1)
result = (num for num in range(6))
for num in result:
print(num)
0
1
2
3
4
5
result = (num for num in range(6))
print(list(result))
[0, 1, 2, 3, 4, 5]
PYTHON DATA SCIENCE TOOLBOX (PART 2)
Printing values from generators (2)
result = (num for num in range(6
Lazy evaluation
print(next(result))
0
print(next(result))
1
print(next(result))
2
print(next(result))
3
print(next(result))
4
PYTHON DATA SCIENCE TOOLBOX (PART 2)
Generators vs list comprehensions
PYTHON DATA SCIENCE TOOLBOX (PART 2)
Generators vs list comprehensions
PYTHON DATA SCIENCE TOOLBOX (PART 2)
Generators vs list comprehensions
PYTHON DATA SCIENCE TOOLBOX (PART 2)
Conditionals in generator expressions
even_nums = (num for num in range(10) if num % 2 == 0)
print(list(even_nums))
[0, 2, 4, 6, 8]
PYTHON DATA SCIENCE TOOLBOX (PART 2)
Generator functions
Produces generator objects when called
De ned like a regular function - def
Yields a sequence of values instead of returning a single value
Generates a value with yield keyword
PYTHON DATA SCIENCE TOOLBOX (PART 2)
Build a generator function
sequence.py
def num_sequence(n):
"""Generate values from 0 to n."""
i = 0
while i < n:
yield i
i += 1
PYTHON DATA SCIENCE TOOLBOX (PART 2)
Use a generator function
result = num_sequence(5)
print(type(result))
<class 'generator'>
for item in result:
print(item)
0
1
2
3
4
Let's practice!
P YTH ON DATA S CIEN CE TOOLBOX (PART 2)
Wrapping up
comprehensions and
generators.
P YTH ON DATA S CIEN CE TOOLBOX (PART 2)
Hugo Bowne-Anderson
Data Scientist at DataCamp
PYTHON DATA SCIENCE TOOLBOX (PART 2)
Re-cap: list comprehensions
Basic
[output expression for iterator variable in iterable]
Advanced
[output expression +
conditional on output for iterator variable in iterable +
conditional on iterable]
Let's practice!
P YTH ON DATA S CIEN CE TOOLBOX (PART 2)

More Related Content

Similar to 2. List Comprehensions and Generators.pdf

PYTHONOr else the work is fine only. Lot to learn buddy.... Improve your basi...
PYTHONOr else the work is fine only. Lot to learn buddy.... Improve your basi...PYTHONOr else the work is fine only. Lot to learn buddy.... Improve your basi...
PYTHONOr else the work is fine only. Lot to learn buddy.... Improve your basi...
Yashpatel821746
 
Profiling and optimization
Profiling and optimizationProfiling and optimization
Profiling and optimization
g3_nittala
 
Task4output.txt 2 5 9 13 15 10 1 0 3 7 11 14 1.docx
Task4output.txt 2  5  9 13 15 10  1  0  3  7 11 14 1.docxTask4output.txt 2  5  9 13 15 10  1  0  3  7 11 14 1.docx
Task4output.txt 2 5 9 13 15 10 1 0 3 7 11 14 1.docx
josies1
 

Similar to 2. List Comprehensions and Generators.pdf (20)

VARIOUS FUZZY NUMBERS AND THEIR VARIOUS RANKING APPROACHES
VARIOUS FUZZY NUMBERS AND THEIR VARIOUS RANKING APPROACHESVARIOUS FUZZY NUMBERS AND THEIR VARIOUS RANKING APPROACHES
VARIOUS FUZZY NUMBERS AND THEIR VARIOUS RANKING APPROACHES
 
Perm winter school 2014.01.31
Perm winter school 2014.01.31Perm winter school 2014.01.31
Perm winter school 2014.01.31
 
R Language Introduction
R Language IntroductionR Language Introduction
R Language Introduction
 
Programs in array using SWIFT
Programs in array using SWIFTPrograms in array using SWIFT
Programs in array using SWIFT
 
TENSOR DECOMPOSITION WITH PYTHON
TENSOR DECOMPOSITION WITH PYTHONTENSOR DECOMPOSITION WITH PYTHON
TENSOR DECOMPOSITION WITH PYTHON
 
Python
PythonPython
Python
 
PMED Undergraduate Workshop - R Tutorial for PMED Undegraduate Workshop - Xi...
PMED Undergraduate Workshop - R Tutorial for PMED Undegraduate Workshop  - Xi...PMED Undergraduate Workshop - R Tutorial for PMED Undegraduate Workshop  - Xi...
PMED Undergraduate Workshop - R Tutorial for PMED Undegraduate Workshop - Xi...
 
‏‏chap6 list tuples.pptx
‏‏chap6 list tuples.pptx‏‏chap6 list tuples.pptx
‏‏chap6 list tuples.pptx
 
Python intro ch_e_comp
Python intro ch_e_compPython intro ch_e_comp
Python intro ch_e_comp
 
Introduction to R programming
Introduction to R programmingIntroduction to R programming
Introduction to R programming
 
QMC: Undergraduate Workshop, Tutorial on 'R' Software - Yawen Guan, Feb 26, 2...
QMC: Undergraduate Workshop, Tutorial on 'R' Software - Yawen Guan, Feb 26, 2...QMC: Undergraduate Workshop, Tutorial on 'R' Software - Yawen Guan, Feb 26, 2...
QMC: Undergraduate Workshop, Tutorial on 'R' Software - Yawen Guan, Feb 26, 2...
 
8799.pdfOr else the work is fine only. Lot to learn buddy.... Improve your ba...
8799.pdfOr else the work is fine only. Lot to learn buddy.... Improve your ba...8799.pdfOr else the work is fine only. Lot to learn buddy.... Improve your ba...
8799.pdfOr else the work is fine only. Lot to learn buddy.... Improve your ba...
 
Or else the work is fine only. Lot to learn buddy.... Improve your basics in ...
Or else the work is fine only. Lot to learn buddy.... Improve your basics in ...Or else the work is fine only. Lot to learn buddy.... Improve your basics in ...
Or else the work is fine only. Lot to learn buddy.... Improve your basics in ...
 
PYTHONOr else the work is fine only. Lot to learn buddy.... Improve your basi...
PYTHONOr else the work is fine only. Lot to learn buddy.... Improve your basi...PYTHONOr else the work is fine only. Lot to learn buddy.... Improve your basi...
PYTHONOr else the work is fine only. Lot to learn buddy.... Improve your basi...
 
Profiling and optimization
Profiling and optimizationProfiling and optimization
Profiling and optimization
 
Seminar psu 20.10.2013
Seminar psu 20.10.2013Seminar psu 20.10.2013
Seminar psu 20.10.2013
 
Study material ip class 12th
Study material ip class 12thStudy material ip class 12th
Study material ip class 12th
 
R Cheat Sheet for Data Analysts and Statisticians.pdf
R Cheat Sheet for Data Analysts and Statisticians.pdfR Cheat Sheet for Data Analysts and Statisticians.pdf
R Cheat Sheet for Data Analysts and Statisticians.pdf
 
Task4output.txt 2 5 9 13 15 10 1 0 3 7 11 14 1.docx
Task4output.txt 2  5  9 13 15 10  1  0  3  7 11 14 1.docxTask4output.txt 2  5  9 13 15 10  1  0  3  7 11 14 1.docx
Task4output.txt 2 5 9 13 15 10 1 0 3 7 11 14 1.docx
 
Python 培训讲义
Python 培训讲义Python 培训讲义
Python 培训讲义
 

Recently uploaded

Tembisa Central Terminating Pills +27838792658 PHOMOLONG Top Abortion Pills F...
Tembisa Central Terminating Pills +27838792658 PHOMOLONG Top Abortion Pills F...Tembisa Central Terminating Pills +27838792658 PHOMOLONG Top Abortion Pills F...
Tembisa Central Terminating Pills +27838792658 PHOMOLONG Top Abortion Pills F...
drjose256
 
Maher Othman Interior Design Portfolio..
Maher Othman Interior Design Portfolio..Maher Othman Interior Design Portfolio..
Maher Othman Interior Design Portfolio..
MaherOthman7
 
21P35A0312 Internship eccccccReport.docx
21P35A0312 Internship eccccccReport.docx21P35A0312 Internship eccccccReport.docx
21P35A0312 Internship eccccccReport.docx
rahulmanepalli02
 

Recently uploaded (20)

Diploma Engineering Drawing Qp-2024 Ece .pdf
Diploma Engineering Drawing Qp-2024 Ece .pdfDiploma Engineering Drawing Qp-2024 Ece .pdf
Diploma Engineering Drawing Qp-2024 Ece .pdf
 
Tembisa Central Terminating Pills +27838792658 PHOMOLONG Top Abortion Pills F...
Tembisa Central Terminating Pills +27838792658 PHOMOLONG Top Abortion Pills F...Tembisa Central Terminating Pills +27838792658 PHOMOLONG Top Abortion Pills F...
Tembisa Central Terminating Pills +27838792658 PHOMOLONG Top Abortion Pills F...
 
UNIT-2 image enhancement.pdf Image Processing Unit 2 AKTU
UNIT-2 image enhancement.pdf Image Processing Unit 2 AKTUUNIT-2 image enhancement.pdf Image Processing Unit 2 AKTU
UNIT-2 image enhancement.pdf Image Processing Unit 2 AKTU
 
Maximizing Incident Investigation Efficacy in Oil & Gas: Techniques and Tools
Maximizing Incident Investigation Efficacy in Oil & Gas: Techniques and ToolsMaximizing Incident Investigation Efficacy in Oil & Gas: Techniques and Tools
Maximizing Incident Investigation Efficacy in Oil & Gas: Techniques and Tools
 
Maher Othman Interior Design Portfolio..
Maher Othman Interior Design Portfolio..Maher Othman Interior Design Portfolio..
Maher Othman Interior Design Portfolio..
 
Intro to Design (for Engineers) at Sydney Uni
Intro to Design (for Engineers) at Sydney UniIntro to Design (for Engineers) at Sydney Uni
Intro to Design (for Engineers) at Sydney Uni
 
Interfacing Analog to Digital Data Converters ee3404.pdf
Interfacing Analog to Digital Data Converters ee3404.pdfInterfacing Analog to Digital Data Converters ee3404.pdf
Interfacing Analog to Digital Data Converters ee3404.pdf
 
Passive Air Cooling System and Solar Water Heater.ppt
Passive Air Cooling System and Solar Water Heater.pptPassive Air Cooling System and Solar Water Heater.ppt
Passive Air Cooling System and Solar Water Heater.ppt
 
NO1 Best Powerful Vashikaran Specialist Baba Vashikaran Specialist For Love V...
NO1 Best Powerful Vashikaran Specialist Baba Vashikaran Specialist For Love V...NO1 Best Powerful Vashikaran Specialist Baba Vashikaran Specialist For Love V...
NO1 Best Powerful Vashikaran Specialist Baba Vashikaran Specialist For Love V...
 
NEWLETTER FRANCE HELICES/ SDS SURFACE DRIVES - MAY 2024
NEWLETTER FRANCE HELICES/ SDS SURFACE DRIVES - MAY 2024NEWLETTER FRANCE HELICES/ SDS SURFACE DRIVES - MAY 2024
NEWLETTER FRANCE HELICES/ SDS SURFACE DRIVES - MAY 2024
 
SLIDESHARE PPT-DECISION MAKING METHODS.pptx
SLIDESHARE PPT-DECISION MAKING METHODS.pptxSLIDESHARE PPT-DECISION MAKING METHODS.pptx
SLIDESHARE PPT-DECISION MAKING METHODS.pptx
 
8th International Conference on Soft Computing, Mathematics and Control (SMC ...
8th International Conference on Soft Computing, Mathematics and Control (SMC ...8th International Conference on Soft Computing, Mathematics and Control (SMC ...
8th International Conference on Soft Computing, Mathematics and Control (SMC ...
 
Working Principle of Echo Sounder and Doppler Effect.pdf
Working Principle of Echo Sounder and Doppler Effect.pdfWorking Principle of Echo Sounder and Doppler Effect.pdf
Working Principle of Echo Sounder and Doppler Effect.pdf
 
Augmented Reality (AR) with Augin Software.pptx
Augmented Reality (AR) with Augin Software.pptxAugmented Reality (AR) with Augin Software.pptx
Augmented Reality (AR) with Augin Software.pptx
 
Instruct Nirmaana 24-Smart and Lean Construction Through Technology.pdf
Instruct Nirmaana 24-Smart and Lean Construction Through Technology.pdfInstruct Nirmaana 24-Smart and Lean Construction Through Technology.pdf
Instruct Nirmaana 24-Smart and Lean Construction Through Technology.pdf
 
handbook on reinforce concrete and detailing
handbook on reinforce concrete and detailinghandbook on reinforce concrete and detailing
handbook on reinforce concrete and detailing
 
CLOUD COMPUTING SERVICES - Cloud Reference Modal
CLOUD COMPUTING SERVICES - Cloud Reference ModalCLOUD COMPUTING SERVICES - Cloud Reference Modal
CLOUD COMPUTING SERVICES - Cloud Reference Modal
 
21P35A0312 Internship eccccccReport.docx
21P35A0312 Internship eccccccReport.docx21P35A0312 Internship eccccccReport.docx
21P35A0312 Internship eccccccReport.docx
 
Theory of Time 2024 (Universal Theory for Everything)
Theory of Time 2024 (Universal Theory for Everything)Theory of Time 2024 (Universal Theory for Everything)
Theory of Time 2024 (Universal Theory for Everything)
 
Adsorption (mass transfer operations 2) ppt
Adsorption (mass transfer operations 2) pptAdsorption (mass transfer operations 2) ppt
Adsorption (mass transfer operations 2) ppt
 

2. List Comprehensions and Generators.pdf

  • 1. List comprehensions P YTH ON DATA S CIEN CE TOOLBOX (PART 2) Hugo Bowne-Anderson Data Scientist at DataCamp
  • 2. PYTHON DATA SCIENCE TOOLBOX (PART 2) Populate a list with a for loop nums = [12, 8, 21, 3, 16] new_nums = [] for num in nums: new_nums.append(num + 1) print(new_nums) [13, 9, 22, 4, 17]
  • 3. PYTHON DATA SCIENCE TOOLBOX (PART 2) A list comprehension nums = [12, 8, 21, 3, 16] new_nums = [num + 1 for num in nums] print(new_nums) [13, 9, 22, 4, 17]
  • 4. PYTHON DATA SCIENCE TOOLBOX (PART 2) For loop and list comprehension syntax new_nums = [num + 1 for num in nums] for num in nums: new_nums.append(num + 1) print(new_nums) [13, 9, 22, 4, 17]
  • 5. PYTHON DATA SCIENCE TOOLBOX (PART 2) List comprehension with range() result = [num for num in range(11)] print(result) [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
  • 6. PYTHON DATA SCIENCE TOOLBOX (PART 2) List comprehensions Collapse for loops for building lists into a single line Components Iterable Iterator variable (represent members of iterable) Output expression
  • 7. PYTHON DATA SCIENCE TOOLBOX (PART 2) Nested loops (1) pairs_1 = [] for num1 in range(0, 2): for num2 in range(6, 8): pairs_1.append(num1, num2) print(pairs_1) [(0, 6), (0, 7), (1, 6), (1, 7)] How to do this with a list comprehension?
  • 8. PYTHON DATA SCIENCE TOOLBOX (PART 2) Nested loops (2) pairs_2 = [(num1, num2) for num1 in range(0, 2) for num2 in range(6, print(pairs_2) [(0, 6), (0, 7), (1, 6), (1, 7)] Tradeoff: readability
  • 9. Let's practice! P YTH ON DATA S CIEN CE TOOLBOX (PART 2)
  • 10. Advanced comprehensions P YTH ON DATA S CIEN CE TOOLBOX (PART 2) Hugo Bowne-Anderson Data Scientist at DataCamp
  • 11. PYTHON DATA SCIENCE TOOLBOX (PART 2) Conditionals in comprehensions Conditionals on the iterable [num ** 2 for num in range(10) if num % 2 == 0] [0, 4, 16, 36, 64] Python documentation on the % operator: The % (modulo) operator yields the remainder from the division of the rst argument by the second. 5 % 2 1 6 % 2 0
  • 12. PYTHON DATA SCIENCE TOOLBOX (PART 2) Conditionals in comprehensions Conditionals on the output expression [num ** 2 if num % 2 == 0 else 0 for num in range(10)] [0, 0, 4, 0, 16, 0, 36, 0, 64, 0]
  • 13. PYTHON DATA SCIENCE TOOLBOX (PART 2) Dict comprehensions Create dictionaries Use curly braces {} instead of brackets [] pos_neg = {num: -num for num in range(9)} print(pos_neg) {0: 0, 1: -1, 2: -2, 3: -3, 4: -4, 5: -5, 6: -6, 7: -7, 8: -8} print(type(pos_neg)) <class 'dict'>
  • 14. Let's practice! P YTH ON DATA S CIEN CE TOOLBOX (PART 2)
  • 15. Introduction to generator expressions P YTH ON DATA S CIEN CE TOOLBOX (PART 2) Hugo Bowne-Anderson Data Scientist at DataCamp
  • 16. PYTHON DATA SCIENCE TOOLBOX (PART 2) Generator expressions Recall list comprehension [2 * num for num in range(10)] [0, 2, 4, 6, 8, 10, 12, 14, 16, 18] Use ( ) instead of [ ] (2 * num for num in range(10)) <generator object <genexpr> at 0x1046bf888>
  • 17. PYTHON DATA SCIENCE TOOLBOX (PART 2) List comprehensions vs. generators List comprehension - returns a list Generators - returns a generator object Both can be iterated over
  • 18. PYTHON DATA SCIENCE TOOLBOX (PART 2) Printing values from generators (1) result = (num for num in range(6)) for num in result: print(num) 0 1 2 3 4 5 result = (num for num in range(6)) print(list(result)) [0, 1, 2, 3, 4, 5]
  • 19. PYTHON DATA SCIENCE TOOLBOX (PART 2) Printing values from generators (2) result = (num for num in range(6 Lazy evaluation print(next(result)) 0 print(next(result)) 1 print(next(result)) 2 print(next(result)) 3 print(next(result)) 4
  • 20. PYTHON DATA SCIENCE TOOLBOX (PART 2) Generators vs list comprehensions
  • 21. PYTHON DATA SCIENCE TOOLBOX (PART 2) Generators vs list comprehensions
  • 22. PYTHON DATA SCIENCE TOOLBOX (PART 2) Generators vs list comprehensions
  • 23. PYTHON DATA SCIENCE TOOLBOX (PART 2) Conditionals in generator expressions even_nums = (num for num in range(10) if num % 2 == 0) print(list(even_nums)) [0, 2, 4, 6, 8]
  • 24. PYTHON DATA SCIENCE TOOLBOX (PART 2) Generator functions Produces generator objects when called De ned like a regular function - def Yields a sequence of values instead of returning a single value Generates a value with yield keyword
  • 25. PYTHON DATA SCIENCE TOOLBOX (PART 2) Build a generator function sequence.py def num_sequence(n): """Generate values from 0 to n.""" i = 0 while i < n: yield i i += 1
  • 26. PYTHON DATA SCIENCE TOOLBOX (PART 2) Use a generator function result = num_sequence(5) print(type(result)) <class 'generator'> for item in result: print(item) 0 1 2 3 4
  • 27. Let's practice! P YTH ON DATA S CIEN CE TOOLBOX (PART 2)
  • 28. Wrapping up comprehensions and generators. P YTH ON DATA S CIEN CE TOOLBOX (PART 2) Hugo Bowne-Anderson Data Scientist at DataCamp
  • 29. PYTHON DATA SCIENCE TOOLBOX (PART 2) Re-cap: list comprehensions Basic [output expression for iterator variable in iterable] Advanced [output expression + conditional on output for iterator variable in iterable + conditional on iterable]
  • 30. Let's practice! P YTH ON DATA S CIEN CE TOOLBOX (PART 2)