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

AI (27) Android (24) AngularJS (1) Assembly Language (2) aws (17) Azure (7) BI (10) book (4) Books (120) C (77) C# (12) C++ (82) Course (64) Coursera (182) Cybersecurity (24) data management (11) Data Science (98) Data Strucures (6) Deep Learning (10) Django (6) Downloads (3) edx (2) Engineering (14) Excel (13) Factorial (1) Finance (6) flutter (1) FPL (17) Google (19) Hadoop (3) HTML&CSS (46) IBM (25) IoT (1) IS (25) Java (92) Leet Code (4) Machine Learning (46) Meta (18) MICHIGAN (5) microsoft (4) Pandas (3) PHP (20) Projects (29) Python (772) Python Coding Challenge (256) Questions (2) R (70) React (6) Scripting (1) security (3) Selenium Webdriver (2) Software (17) SQL (40) UX Research (1) web application (8)

Followers

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