- Python Basics
-
Overview
- Introduction to Python and Installation
- Variables and Data Types
- Conditional Statements (if-else)
- Loops (for, while)
- Functions and Lambda Expressions
- Lists, Tuples, and Dictionaries
- File Handling (Reading/Writing Files)
- Exception Handling (Try, Except)
- Modules and Packages
- List Comprehensions and Generators
List Comprehensions and Generators
1. Introduction
Python provides efficient ways to handle collections of data using list comprehensions and generators.
- List comprehensions offer a concise way to create lists.
- Generators help in memory-efficient iteration by generating values on the fly.
Let's explore both in detail!
2. List Comprehensions
List comprehension provides a compact way to generate a new list from an existing sequence.
Syntax:
new_list = [expression for item in iterable if condition]
Example 1: Creating a List Using a Loop
Without list comprehension:
numbers = [1, 2, 3, 4, 5]
squared = []
for num in numbers:
squared.append(num ** 2)
print(squared) # Output: [1, 4, 9, 16, 25]
With list comprehension:
squared = [num ** 2 for num in numbers]
print(squared) # Output: [1, 4, 9, 16, 25]
More concise and readable!
Example 2: List Comprehension with Condition
even_numbers = [num for num in range(10) if num % 2 == 0]
print(even_numbers) # Output: [0, 2, 4, 6, 8]
Filters only even numbers
Example 3: Nested List Comprehensions
matrix = [[j for j in range(3)] for i in range(3)]
print(matrix)
# Output: [[0, 1, 2], [0, 1, 2], [0, 1, 2]]
Creates a 3×3 matrix using nested list comprehension
3. Generators in Python
A generator is a function that yields values one at a time, saving memory compared to storing all values in a list.
Creating a Generator Function
def count_up_to(n):
count = 1
while count <= n:
yield count
count += 1
gen = count_up_to(5)
print(next(gen)) # Output: 1
print(next(gen)) # Output: 2
Generators do not store values in memory; they generate values on demand.
4. Generator Expressions (Like List Comprehensions but Lazy)
Just like list comprehensions, but using parentheses ()
instead of brackets []
gen_exp = (x * 2 for x in range(5))
print(next(gen_exp)) # Output: 0
print(next(gen_exp)) # Output: 2
Saves memory, especially useful for large data sets.
5. Key Differences Between List Comprehensions and Generators
Feature | List Comprehension | Generator |
---|---|---|
Syntax | [expression for item in iterable] | (expression for item in iterable) |
Execution | Stores all values in memory | Generates values one at a time |
Performance | Faster for small datasets | More memory-efficient for large datasets |
Use case | When you need the whole list at once | When iterating over a large dataset |
6. Summary
List comprehensions create lists efficiently in a single line.
Generators produce values lazily, saving memory.
Use list comprehensions when working with small datasets.
Use generators when dealing with large datasets or infinite sequences.
Prepare for Interview
- Debugging in Python
- Multithreading and Multiprocessing in Python
- Context Managers in Python
- Decorators in Python
- Generators in Python
- Requests in Python
- Django
- Flask
- Matplotlib/Seaborn
- Pandas
- NumPy
- Modules and Packages in Python
- File Handling in Python
- Error Handling and Exceptions in Python
- Indexing and Performance Optimization in SQL
Random Blogs
- 15 Amazing Keyword Research Tools You Should Explore
- How AI is Making Humans Weaker – The Hidden Impact of Artificial Intelligence
- AI in Cybersecurity: The Future of Digital Protection
- Role of Digital Marketing Services to Uplift Online business of Company and Beat Its Competitors
- Career Guide: Natural Language Processing (NLP)
- Internet of Things (IoT) & AI – Smart Devices and AI Working Together
- Types of Numbers in Python
- The Ultimate Guide to Machine Learning (ML) for Beginners
- Top 10 Blogs of Digital Marketing you Must Follow
- Quantum AI – The Future of AI Powered by Quantum Computing
- Data Analytics: The Power of Data-Driven Decision Making
- Store Data Into CSV File Using Python Tkinter GUI Library
- What is YII? and How to Install it?
- Grow your business with Facebook Marketing
- Top 10 Knowledge for Machine Learning & Data Science Students
Datasets for Machine Learning
- Ozone Level Detection Dataset
- Bank Transaction Fraud Detection
- YouTube Trending Video Dataset (updated daily)
- Covid-19 Case Surveillance Public Use Dataset
- US Election 2020
- Forest Fires Dataset
- Mobile Robots Dataset
- Safety Helmet Detection
- All Space Missions from 1957
- OSIC Pulmonary Fibrosis Progression Dataset
- Wine Quality Dataset
- Google Audio Dataset
- Iris flower dataset
- Artificial Characters Dataset
- Bitcoin Heist Ransomware Address Dataset