Sunday, 19 May 2024

Python List Comprehensions

List comprehensions in Python provide a powerful and concise way to create lists. They are an essential part of any Python programmer's toolkit. Ready to make your code more Pythonic? Let's dive in!

What is a List Comprehension?

A list comprehension is a compact way to process all or part of the elements in a sequence and return a list with the results. The syntax is simple yet powerful:

[expression for item in iterable if condition]

Basic Example

Let's start with a basic example. Suppose we want a list of squares for numbers from 0 to 9. With list comprehensions, it's a one-liner:

squares = [x**2 for x in range(10)]

print(squares)

Output:

[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

Adding a Condition

What if we want only even squares? Just add an if condition at the end:

even_squares = [x**2 for x in range(10) if x % 2 == 0]

print(even_squares)

Output:

[0, 4, 16, 36, 64]

Nested Comprehensions

You can also nest comprehensions for multidimensional lists. Here’s an example to flatten a 2D list:

matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

flattened = [num for row in matrix for num in row]

print(flattened)

Output:

[1, 2, 3, 4, 5, 6, 7, 8, 9]

Dictionary Comprehensions

List comprehensions aren’t just for lists. You can create dictionaries too!

squares_dict = {x: x**2 for x in range(10)}

print(squares_dict)

Output:

{0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81}

Set Comprehensions

And even sets! This creates a set of unique squares:

unique_squares = {x**2 for x in range(10)}

print(unique_squares)

Output:

{0, 1, 4, 9, 16, 25, 36, 49, 64, 81}

Advanced Use - Function Application

You can apply functions within comprehensions. Here’s an example using str.upper():

words = ["hello", "world", "python"]

upper_words = [word.upper() for word in words]

print(upper_words)

Output:

['HELLO', 'WORLD', 'PYTHON']

Comprehensions with Multiple Conditions

You can add multiple conditions. Let’s filter numbers divisible by 2 and 3:

filtered = [x for x in range(20) if x % 2 == 0 if x % 3 == 0]

print(filtered)

Output:

[0, 6, 12, 18]

In Conclusion

List comprehensions make your code cleaner and more readable. They’re efficient and Pythonic. Practice and integrate them into your projects to see the magic!

0 Comments:

Post a Comment

Popular Posts

Categories

100 Python Programs for Beginner (13) AI (33) Android (24) AngularJS (1) Assembly Language (2) aws (17) Azure (7) BI (10) book (4) Books (161) C (77) C# (12) C++ (82) Course (67) Coursera (223) Cybersecurity (24) data management (11) Data Science (127) Data Strucures (8) Deep Learning (20) Django (14) Downloads (3) edx (2) Engineering (14) Excel (13) Factorial (1) Finance (6) flask (3) flutter (1) FPL (17) Google (34) Hadoop (3) HTML&CSS (47) IBM (25) IoT (1) IS (25) Java (93) Leet Code (4) Machine Learning (53) Meta (22) MICHIGAN (5) microsoft (4) Nvidia (1) Pandas (3) PHP (20) Projects (29) Python (917) Python Coding Challenge (304) Questions (2) R (70) React (6) Scripting (1) security (3) Selenium Webdriver (2) Software (17) SQL (42) UX Research (1) web application (8)

Followers

Person climbing a staircase. Learn Data Science from Scratch: online program with 21 courses