- 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: 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
- 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
- Debugging in Python
- Unit Testing in Python
- Asynchronous Programming in PYthon
- Multithreading and Multiprocessing in Python
- Context Managers in Python
Random Blogs
- Types of Numbers in Python
- SQL Joins Explained: A Complete Guide with Examples
- Mastering SQL in 2025: A Complete Roadmap for Beginners
- The Ultimate Guide to Starting a Career in Computer Vision
- Python Challenging Programming Exercises Part 1
- Important Mistakes to Avoid While Advertising on Facebook
- OLTP vs. OLAP Databases: Advanced Insights and Query Optimization Techniques
- Understanding AI, ML, Data Science, and More: A Beginner's Guide to Choosing Your Career Path
- Top 15 Recommended SEO Tools
- Store Data Into CSV File Using Python Tkinter GUI Library
- Where to Find Free Datasets for Your Next Machine Learning & Data Science Project
- Datasets for Natural Language Processing
- What is YII? and How to Install it?
- Why to learn Digital Marketing?
- What Is SEO and Why Is It Important?
Datasets for Machine Learning
- 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
- Artificial Characters Dataset