Python Data Science Jobs & Interviews
20.4K subscribers
188 photos
4 videos
25 files
327 links
Your go-to hub for Python and Data Science—featuring questions, answers, quizzes, and interview tips to sharpen your skills and boost your career in the data-driven world.

Admin: @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