Discover Python: Daily Questions for All Levels.

Welcome to our daily Python challenge! As lovers and enthusiasts of this amazing language, we have created a space where you can improve your skills and test your knowledge every day.

Each day, we’ll post a new Python question, covering everything from basic concepts to advanced topics. Whether you’re a beginner eager to learn or an experienced programmer looking for a new challenge, our exercises are designed for everyone. Join us on this continuous learning journey.

🔔 Subscribe to the InfinitePy Newsletter for more resources and a step-by-step approach to learning Python, and stay up to date with the latest trends and practical tips.

All examples are also explained here 👨‍🔬, a Google Colab notebook to make your learning even more interactive.

InfinitePy Newsletter - Your source for Python learning and inspiration.

Question • 83C4

October 08, 2024

What is the output for the Python code below?

def my_function(lst):
    lst.append(4)

my_list = [1, 2, 3]
my_function(my_list)

print(my_list)

Answer

[1, 2, 3, 4]

Let's analyze the code step by step:

# Define a function named my_function that takes a single argument lst
def my_function(lst):
    # The append() method adds a single item (in this case, the number 4)
    # to the end of the list 'lst'. Lists in Python are mutable, meaning
    # they can be changed after their creation, and methods like append
    # modify the list in place.
    lst.append(4)

# Create a list named my_list containing three integers: 1, 2, and 3
# Lists are ordered collections in Python, where elements are
# stored in the order they are inserted.
my_list = [1, 2, 3]

# Call the function my_function, passing my_list as an argument.
# Since lists are mutable, the function will change the original
# list object directly.
my_function(my_list)

# Print the my_list to the console. Since my_function appended
# the number 4 to the list, the output will be: [1, 2, 3, 4]
# This demonstrates that changes to the list within the function
# are reflected in the calling environment.
print(my_list)

Question • 8159

October 07, 2024

What is the output for the Python code below?

s = ["newsletter", "about", "Python"]
sentence = "-".join(s)
print(sentence)

Answer

newsletter-about-Python

Let's analyze the code step by step:

# Define a list of strings. Each string in the list represents a different word or concept.
s = ["newsletter", "about", "Python"]

# Use the join() method on a string, which is represented through a delimiter "-".
# The join() method combines all elements of the iterable (in this case, 's' list)
# into a single string, with the delimiter "-" inserted between each element.
sentence = "-".join(s)

# Print out the resulting string to the console.
# This will output the combined string with "-" between each original string from the list.
print(sentence)

Question • 6ABB

October 04, 2024

What is the output for the Python code below?

student_scores = {'Daniel': 85, 'Victor': 90, 'Julia': 92}
anna_score = student_scores.get('Anna', 70)
print(anna_score)

Answer

70

Let's analyze the code step by step:

# Import the NumPy library
# NumPy is a powerful library in Python used for numerical computations
# It provides support for arrays, and mathematical functions to operate on these arrays
import numpy as np

# Create a NumPy array 'a' with elements 1, 2, and 3
# NumPy arrays are similar to Python lists but allow for efficient array operations
a = np.array([1, 2, 3])

# Create another NumPy array 'b' with elements 4, 5, and 6
b = np.array([4, 5, 6])

# Add the two arrays 'a' and 'b'
# NumPy allows element-wise operations, which means this operation will add corresponding elements
# In this case, it will add the first element of 'a' to the first element of 'b', and so on
# Result: c = np.array([1+4, 2+5, 3+6]) = np.array([5, 7, 9])
c = a + b

# Print the result
# This will display the resulting array from the addition of arrays 'a' and 'b'
print(c)

Question • 59FD

October 03, 2024

What is the output for the Python code below?

c = {'🔴', '🟡', '🟢'}
c.discard('🔵')
print(c)

Answer

{'🟢', '🟡', '🔴'}

Let's analyze the code step by step:

# Initialize a set 'c' with three colored emoji elements: red circle, yellow circle, and green circle.
c = {'🔴', '🟡', '🟢'}

# Attempt to remove the element '🔵' (blue circle) from the set 'c'.
# The discard method is used here. If '🔵' is present in the set, it will be removed.
# If '🔵' is not present, discard does nothing and does not raise an error.
c.discard('🔵')

# Print the set 'c' to the console.
# Expected output is the original set {'🔴', '🟡', '🟢'} since '🔵' was not part of the set and therefore nothing was removed.
print(c)

Question • 89DB

October 02, 2024

What is the output for the Python code below?

from datetime import datetime
dt = datetime(2024, 10, 2, 14, 10, 00)
print(f"{dt:%a, %d %b %Y %H:%M:%S}")

Answer

Wed, 02 Oct 2024 14:10:00

Let's analyze the code step by step:

# Importing the 'datetime' class from the 'datetime' module
# The 'datetime' module provides classes for manipulating dates and times.
from datetime import datetime

# Creating a 'datetime' object for a specific date and time
# The 'datetime' function takes several parameters: year, month, day, hour, minute, second
# In this case, it's creating a datetime object for October 2, 2024, at 14:10:00 (2:10 PM)
dt = datetime(2024, 10, 2, 14, 10, 00)

# Printing the formatted date and time using an f-string
# An f-string is a string literal that is prefixed with 'f' or 'F'
# It allows for embedded Python expressions inside string constants
# In this case, the expression '{dt:%a, %d %b %Y %H:%M:%S}' formats the 'dt' object
# %a - Abbreviated weekday name ('Wed' for Wednesday)
# %d - Day of the month as a zero-padded number (02)
# %b - Abbreviated month name ('Oct' for October)
# %Y - Year with century (2024)
# %H - Hour (00-23, 24-hour clock) (14, which is 2 PM)
# %M - Minute (00-59) (10)
# %S - Second (00-59) (00)
print(f"{dt:%a, %d %b %Y %H:%M:%S}")

Question • AC9B

October 01, 2024

What is the output for the Python code below?

x = {10, 20, 30, 40}
y = {30, 40, 50, 60}

sd = x.symmetric_difference(y)
print(sd)

Answer

{10, 50, 20, 60}

Let's analyze the code step by step:

# Initialize set x with four elements: 10, 20, 30, and 40
x = {10, 20, 30, 40}

# Initialize set y with four elements: 30, 40, 50, and 60
y = {30, 40, 50, 60}

# Use the symmetric_difference() method to find elements that are in either
# of the sets x or y, but not in both. The symmetric difference of two sets
# returns a set with elements that are unique to each of them, essentially 
# excluding the common elements found in both sets.
sd = x.symmetric_difference(y)

# Print the resulting set stored in 'sd', which contains the symmetric 
# difference. Here, you should expect to see: {10, 20, 50, 60}. These are the 
# elements that are either in set x or set y, but not in both.
print(sd)

Question • 4BEA

September 30, 2024

What is the output for the Python code below?

from functools import reduce

numbers = [2, 3, 4]
p = reduce(lambda x, y: x * y, numbers)
print(p)

Answer

24

Let's analyze the code step by step:

# Import the 'reduce' function from the 'functools' module
# - The 'functools' module is a standard library module that provides tools for functional programming.
# - 'reduce' is a function that applies a rolling computation to sequential pairs of values in a list.
from functools import reduce

# Define a list of numbers for which we want to calculate the product
# - This is a simple list containing three integers: 2, 3, and 4.
numbers = [2, 3, 4]

# Use 'reduce' to calculate the product of all numbers in the list
# - The 'reduce' function takes two arguments: a lambda function and an iterable (in this case, the list 'numbers').
# - The lambda function is basically an anonymous function that takes two arguments, x and y.
# - The lambda function returns the product of x and y.
# - 'reduce' will apply this lambda function cumulatively to the items in the list.
# - For the list [2, 3, 4], this means: ((((2 * 3) * 4)) = 24
p = reduce(lambda x, y: x * y, numbers)

# Print the result of the computation
# - In this case, it will print the product of the numbers in the list, which is 24.
print(p)

Question • 4F00

September 27, 2024

What is the output for the Python code below?

s = "InfinitePy, Python weekly newsletter."
result = s[3:25:3]
result = result.upper()
print(result)

Answer

ITYPH EY

Let's analyze the code step by step:

# This is a string variable that contains the sentence
s = "InfinitePy, Python weekly newsletter."

# Slice the string from index 3 to index 25, taking every 3rd character.
# Slicing format: [start:stop:step]
# s[3:25:3] - start at index 3, stop before index 25, take every 3rd character
# The resulting slice includes characters at indices 3, 6, 9, ..., 24
result = s[3:25:3]

# Convert the sliced string to uppercase
# The upper() method converts all lowercase characters in the string to uppercase
result = result.upper()

# Print the resulting uppercase string to the console
print(result)

Question • 4E0C

September 26, 2024

What is the output for the Python code below?

num = [26, 9, 2024, 52, 18, 4048]
print( all(n > 0 for n in num) )

Answer

True

Let's analyze the code step by step:

# Define a list of integers named 'num'
num = [26, 9, 2024, 52, 18, 4048]

# Use the built-in 'all()' function to evaluate a condition (n > 0) for each element 'n' in the list 'num'
# The 'all()' function returns True if all elements in the iterable (here, the generator expression) are True
print(all(n > 0 for n in num))

# Explanation of the generator expression 'n > 0 for n in num':
# - 'for n in num' iterates over the list 'num', assigning each element to the variable 'n' one at a time.
# - 'n > 0' is a condition that is checked for each element. It returns True if the number 'n' is greater than zero.
# 
# The generator expression 'n > 0 for n in num' efficiently checks if all numbers in the list 'num' are greater than zero without creating an unnecessary list in memory.
# 
# If all numbers in the list are greater than zero, the 'all()' function will return True, and hence the print statement will output 'True'.
# If any number in the list is less than or equal to zero, 'all()' will return False, and the output will be 'False'.

Question • 7022

September 25, 2024

What is the output for the Python code below?

lst = [0, 1]
[lst.append(lst[k - 1] + lst[k - 2]) for k in range(2, 5)]
print(lst)

Answer

[0, 1, 1, 2, 3]

Let's analyze the code step by step:

# Initialize a list 'lst' with the first two elements of the Fibonacci sequence
lst = [0, 1]

# This is a list comprehension which is being used to iterate over a range.
# But here, its main purpose is to execute the append operation on the list 'lst' for each value of 'k'.
# Typically, list comprehensions are used for generating lists, but here it's used deliberately to modify 'lst'.
# We iterate over 'range(2, 5)', which generates a sequence of numbers [2, 3, 4].

[lst.append(lst[k - 1] + lst[k - 2]) for k in range(2, 5)]

# Here’s the breakdown inside the list comprehension for each 'k':
# - When k = 2: lst.append(lst[1] + lst[0]) adds (1 + 0 = 1) to lst. Now lst = [0, 1, 1].
# - When k = 3: lst.append(lst[2] + lst[1]) adds (1 + 1 = 2) to lst. Now lst = [0, 1, 1, 2].
# - When k = 4: lst.append(lst[3] + lst[2]) adds (2 + 1 = 3) to lst. Now lst = [0, 1, 1, 2, 3].

# After the comprehension has completed, it doesn't create any new list as it usually does.
# Instead, it performs side-effects (modifying the existing list).

# Print the final list, which now contains the first five Fibonacci numbers: [0, 1, 1, 2, 3]
print(lst)

Question • CFCF

September 24, 2024

What is the output for the Python code below?

lst = [10]
lst_iter = iter(lst)
print(next(lst_iter))

Answer

10

Let's analyze the code step by step:

# Define a list called `lst` with three numerical elements. 
lst = [10, 20, 30]  # A list of integers

# Create an iterator object from the list `lst` using the `iter()` function.
# An iterator is an object that allows you to traverse through all the elements of a collection (like a list), one at a time.
lst_iter = iter(lst)  # Creating an iterator for the list

# Use the `next()` function to retrieve the next item from the iterator `lst_iter`.
# In this context, `next()` will return the first element of the list because the iterator is currently positioned at the start.
# Subsequent calls to `next(lst_iter)` would return the second, third elements, and so on, until it exhausts the list.
# If you call `next(lst_iter)` more times than there are elements in the list, it will raise a 'StopIteration' exception.
print(next(lst_iter))  # Print the first item of the iterator, which is `10`

Question • BA05

September 23, 2024

What is the output for the Python code below?

x = {10, 20, 30, 40}
y = {30, 40, 50, 60}

r1 = x.intersection(y)
print(r1)

Answer

{40, 30}

Let's analyze the code step by step:

# Define a set 'x' with four elements: 10, 20, 30, and 40
x = {10, 20, 30, 40}

# Define another set 'y' with four elements: 30, 40, 50, and 60
y = {30, 40, 50, 60}

# Use the 'intersection' method of set 'x' to find elements common to both sets 'x' and 'y'
# The intersection method returns a new set containing elements that appear in both x and y
r1 = x.intersection(y)

# Print the resulting set 'r1' which should contain the elements that are common in both sets
print(r1)  # Expected output: {30, 40}

# Additional breakdown of the intersection process:
# 1. Look at each element in 'x': 10, 20, 30, 40
# 2. Check if these elements are also in 'y': 30, 40, 50, 60
# 3. The elements that appear in both sets are 30 and 40
# 4. The intersection method captures these common elements and 'r1' stores the result: {30, 40}

Question • FC66

September 13, 2024

What is the output for the Python code below?

x = {'a' : 10, 'b' : 20}
y = {'b' : 30, 'c' : 40}

z = {**x, **y}
print(z)

Answer

{'a': 10, 'b': 30, 'c': 40}

Let's analyze the code step by step:

# Create a dictionary 'x' with two key-value pairs: 'a' is paired with 10, and 'b' is paired with 20.
x = {'a': 10, 'b': 20}

# Create another dictionary 'y' with two key-value pairs: 'b' is paired with 30, and 'c' is paired with 40.
y = {'b': 30, 'c': 40}

# Use dictionary unpacking to merge dictionaries 'x' and 'y' into a new dictionary 'z'.
# The syntax {**x, **y} uses the double asterisk (**) to unpack the contents of the dictionaries.
# This syntax allows us to merge or combine dictionaries in Python.
# If there are overlapping keys (like 'b' in this example), the value from the second dictionary ('y') will overwrite the value from the first dictionary ('x').
z = {**x, **y}

# Print the resulting merged dictionary 'z' to the console.
# Expected output is: {'a': 10, 'b': 30, 'c': 40}
# Explanation of the output:
# - 'a': Comes from 'x', as 'y' doesn't have it, so ('a': 10) stays as is.
# - 'b': Both dictionaries have this key, but 'y' has the value 30, which overwrites 'x's value 20 for the key 'b'.
# - 'c': Comes from 'y', as 'x' doesn't have it, so ('c': 40) is included.
print(z)