- 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
Add to Bookmark1. 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: 2Generators 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: 2Saves 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
- JavaScript Interview Questions for 5+ Years Experience
- JavaScript Interview Questions for 2–5 Years Experience
- JavaScript Interview Questions for 1–2 Years Experience
- JavaScript Interview Questions for 0–1 Year Experience
- JavaScript Interview Questions For Fresher
- SQL Interview Questions for 5+ Years Experience
- SQL Interview Questions for 2–5 Years Experience
- SQL Interview Questions for 1–2 Years Experience
- SQL Interview Questions for 0–1 Year Experience
- SQL Interview Questions for Freshers
- Design Patterns in Python
- Dynamic Programming and Recursion in Python
- Trees and Graphs in Python
- Linked Lists, Stacks, and Queues in Python
- Sorting and Searching in Python
Random Blogs
- The Beginner’s Guide to Normalization and Denormalization in Databases
- Grow your business with Facebook Marketing
- Understanding SQL vs MySQL vs PostgreSQL vs MS SQL vs Oracle and Other Popular Databases
- OLTP vs. OLAP Databases: Advanced Insights and Query Optimization Techniques
- Transforming Logistics: The Power of AI in Supply Chain Management
- How Multimodal Generative AI Will Change Content Creation Forever
- How AI Companies Are Making Humans Fools and Exploiting Their Data
- Generative AI - The Future of Artificial Intelligence
- AI in Cybersecurity: The Future of Digital Protection
- What Is SEO and Why Is It Important?
- Career Guide: Natural Language Processing (NLP)
- Exploratory Data Analysis On Iris Dataset
- Convert RBG Image to Gray Scale Image Using CV2
- What is YII? and How to Install it?
- SQL vs MySQL: The Ultimate Guide for Beginners
Datasets for Machine Learning
- Awesome-ChatGPT-Prompts
- Amazon Product Reviews Dataset
- 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


