Create lists in just one line of code! It's like telling Python exactly what you want in your shopping basket! 🛒
List comprehensions are a shortcut way to create lists in Python. They let you create a new list by transforming or filtering elements from another list (or any iterable) in a single line of code!
Basic syntax: [expression for item in iterable (if condition)]
squares = [x**2 for x in range(5)]They're usually quicker than regular loops!
One line instead of 3-4 lines!
Once you get used to them!
One line does the work of many! ✨
[x**2 for x in range(5)] - Squares of numbers 0-4
[x for x in range(10) if x % 2 == 0] - Even numbers 0-9
[ch for ch in "Tesla"] - Characters in a string
table = [[x * y for x in range(1, 6)] for y in range(1, 6)]
This creates a 5×5 multiplication table with just one line of code!
nested_list = [[1, 2], [3, 4], [5, 6]]
flat_list = [item for sublist in nested_list for item in sublist]
[1, 2, 3, 4, 5, 6]
This takes a list of lists and "flattens" it into a single list!
word = "Tesla"
without_vowels = [ch for ch in word if ch.lower() not in "aeiou"]
['T', 's', 'l']
Like removing all the vowels from your secret code message! 🕵️
colors = ["red", "blue"]
sizes = ["small", "medium"]
combinations = [(color, size) for color in colors for size in sizes]
Like creating all possible t-shirt combinations in your store! 👕
[expression for item in iterable]
Creates a new list by applying the expression to each item
[expression for item in iterable if condition]
Only includes items that meet the condition
[expression for item1 in iterable1 for item2 in iterable2]
Loops through two iterables (like nested for loops)
[[expression for item1 in iterable1] for item2 in iterable2]
Creates a list of lists (like a 2D array)