PyData Careers
20.8K subscribers
205 photos
4 videos
26 files
351 links
Python Data Science jobs, interview tips, and career insights for aspiring professionals.

Admin: @HusseinSheikho || @Hussein_Sheikho
Download Telegram
Python's List Comprehensions provide a compact and elegant way to create lists. They offer a more readable and often more performant alternative to traditional loops for list creation and transformation.

# Create a list of squares using a traditional loop
squares_loop = []
for i in range(5):
squares_loop.append(i i)
print(f"Traditional loop: {squares_loop}")

Achieve the same with a list comprehension

squares_comprehension = [i i for i in range(5)]
print(f"List comprehension: {squares_comprehension}")

List comprehension with a condition (even numbers only)

even_numbers_squared = [i * i for i in range(10) if i % 2 == 0]
print(f"Even numbers squared: {even_numbers_squared}")


Output:
Traditional loop: [0, 1, 4, 9, 16]
List comprehension: [0, 1, 4, 9, 16]
Even numbers squared: [0, 4, 16, 36, 64]

#Python #ListComprehensions #PythonTips #CodeOptimization #Programming #DataStructures #PythonicCode

---
By: @DataScienceQ 🧡
Please open Telegram to view this post
VIEW IN TELEGRAM
Combine multiple iterables into one with zip()!

Instead of:
names = ['Alice', 'Bob', 'Charlie']
ages = [30, 24, 35]
for i in range(len(names)):
print(f"{names[i]} is {ages[i]} years old.")


Use zip() for a cleaner and more Pythonic approach:
names = ['Alice', 'Bob', 'Charlie']
ages = [30, 24, 35]
for name, age in zip(names, ages):
print(f"{name} is {age} years old.")

zip() stops when the shortest iterable is exhausted. Perfect for parallel iteration!

#PythonTip #ZipFunction #Iterators #PythonicCode

---
By: @DataScienceQ
🧠 Quiz: Which Pythonic approach is generally preferred for creating a new list by transforming elements from an existing list?

A) Using a for loop with list.append()
B) Using a list comprehension
C) Using the map() function followed by list()
D) Using a while loop with list.append()

Correct answer: B

Explanation: List comprehensions are often more concise, readable, and generally more performant than explicit for loops or map() for creating new lists based on existing iterables. They encapsulate the iteration and creation logic cleanly.

#PythonTips #PythonicCode #ListComprehensions

---
By: @DataScienceQ
1