Python Data Science Jobs & Interviews
20.4K subscribers
188 photos
4 videos
25 files
326 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
In Python, a list comprehension is a concise and elegant way to create lists. It allows you to generate a new list by applying an expression to each item in an existing iterable (like a list or range), often in a single line of code, making it more readable and compact than a traditional for loop.

# Traditional way using a for loop
squares_loop = []
for i in range(10):
    squares_loop.append(i i)

print(f"Using a loop: {squares_loop}")

The Pythonic way using a list comprehension

squares_comp = [i i for i in range(10)]

print(f"Using comprehension: {squares_comp}")

You can also add conditions

even_squares = [i * i for i in range(10) if i % 2 == 0]
print(f"Even squares only: {even_squares}")

Both the loop and the basic list comprehension produce the exact same result: a list of the first 10 square numbers. However, the list comprehension is more efficient and easier to read once you are familiar with the syntax.

#Python #ListComprehension #PythonTips #CodeExamples #Programming #Pythonic #Developer #Code

By: @DataScienceQ 🩵
Please open Telegram to view this post
VIEW IN TELEGRAM
Python Tip: Tuple Unpacking for Multiple Assignments

Assigning multiple variables at once from a sequence can be done elegantly using tuple unpacking (also known as sequence unpacking). It's clean and efficient.

Traditional way:
coordinates = (10, 20)
x = coordinates[0]
y = coordinates[1]
print(f"X: {x}, Y: {y}")


Using Tuple Unpacking:
coordinates = (10, 20)
x, y = coordinates
print(f"X: {x}, Y: {y}")


This also works with lists and functions that return multiple values. It's often used for swapping variables without a temporary variable:

a = 5
b = 10
a, b = b, a # Swaps values of a and b
print(f"a: {a}, b: {b}") # Output: a: 10, b: 5


#PythonTip #TupleUnpacking #Assignment #Pythonic #Coding
---
By: @DataScienceQ
🧠 Quiz: Which of the following is the most Pythonic and efficient way to iterate through a list my_list and access both each item and its corresponding index?

A) i = 0; while i < len(my_list): item = my_list[i]; i += 1
B) for index, item in enumerate(my_list):
C) for index in range(len(my_list)): item = my_list[index]
D) for item in my_list: index = my_list.index(item)

Correct answer: B

Explanation: The enumerate() function is specifically designed to provide both the index and the item while iterating over a sequence, making the code cleaner, more readable, and generally more efficient than manual indexing or while loops. Option D is inefficient as list.index(item) scans the list for each item, especially if duplicates exist.

#PythonTips #Pythonic #Programming

━━━━━━━━━━━━━━━
By: @DataScienceQ