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 • E961

October 25, 2024

What is the output for the Python code below?

def x(n):
    return n ** 2

n = [1, 2, 3, 4]
result = list(map(x, 

Answer

[1, 4, 9, 16]

Let's analyze the code step by step:

# Define a function `x` that takes one argument `n`.
def x(n):
    # Return the square of `n` using the exponentiation operator `**`.
    return n ** 2

# Create a list `n` containing a sequence of integers.
n = [1, 2, 3, 4]

# Use the `map` function to apply the function `x` to each element in the list `n`.
# `map(x, n)` returns an iterator where `x` has been applied to each element of `n`.
# We convert the resulting map object to a list using the `list()` constructor.
result = list(map(x, n))

# Print out the list `result`, which should contain the squares of the elements in `n`.
print(result)

Question • 85B9

October 24, 2024

What is the output for the Python code below?

list1 = ['a', 'b', 'c']
list2 = [1, 2, 3]
zipped = list(zip(list1, list2))

print(zipped)

Answer

{'a': [], 'b': [2], 'c': [], 'd': []}

Let's analyze the code step by step:

# Step 1: Create the first list of strings
list1 = ['a', 'b', 'c']

# Step 2: Create the second list of integers
list2 = [1, 2, 3]

# Step 3: Use the zip function to combine the lists
zipped = list(zip(list1, list2))
# The 'zip' function takes two (or more) iterables and returns an iterator of tuples
# Each tuple contains elements from the provided iterables, pairing elements with the same index
# e.g., ('a', 1), ('b', 2), ('c', 3)

# 'list' is used to convert the zip object (which is an iterator) into a list of tuples
# The resulting list 'zipped' contains tuples that pair corresponding elements from 'list1' and 'list2'

# Step 4: Print the combined list of tuples
print(zi

Question • 420B

October 23, 2024

What is the output for the Python code below?

l = ['a', 'b', 'c', 'd']
d = {k: [] for k in l}
d['b'].append(2)

print(d)

Answer

{'a': [], 'b': [2], 'c': [], 'd': []}

Let's analyze the code step by step:

# Initialize a list `l` with four different character strings: 'a', 'b', 'c', 'd'.
l = ['a', 'b', 'c', 'd']

# Create a dictionary comprehension to initialize a dictionary `d`.
# Each element of list `l` becomes a key in the dictionary `d`.
# The value assigned to each key is an empty list `[]`.

# Here, `{k: [] for k in l}` is the comprehension part:
# - `k` iterates over each element in list `l`.
# - `k: []` creates a key-value pair for dictionary `d` with `k` as the key and an empty list as the value.

d = {k: [] for k in l}

# Now the dictionary `d` looks like this: 
# {'a': [], 'b': [], 'c': [], 'd': []}

# Use the `append()` method to add the element `2` to the list associated with the key 'b' in the dictionary `d`.
# The key 'b' is used to access the empty list, and `2` is appended to this list.

d['b'].append(2)

# Now the dictionary `d` looks like this:
# {'a': [], 'b': [2], 'c': [], 'd': []}

# Print the dictionary `d` to the console. 
# It will display: {'a': [], 'b': [2], 'c': [], 'd': []}
print(d)

Question • 49E5

October 22, 2024

What is the output for the Python code below?

import itertools

list1 = [1, 2]
list2 = ['a', 'b']
result = list(itertools.product(list1, list2))
print(result)

Answer

[(1, 'a'), (1, 'b'), (2, 'a'), (2, 'b')]

Let's analyze the code step by step:

# Import the itertools module, which is a standard library module in Python.
# It provides functions that create iterators for efficient looping.
import itertools

# Define a list named list1 containing integers 1 and 2.
list1 = [1, 2]

# Define a second list named list2 containing strings 'a' and 'b'.
list2 = ['a', 'b']

# Use itertools.product to compute the Cartesian product of list1 and list2.
# The Cartesian product of two sets is a set of all possible pairs (combinations)
# where the first element of the pair comes from the first set and the second element
# comes from the second set.
# itertools.product takes the input iterables (in this case, list1 and list2),
# and returns an iterator that produces tuples representing the Cartesian product.
# Convert the resulting iterator into a list to be able to easily view and print the output.
result = list(itertools.product(list1, list2))

# Print the result to display the Cartesian product.
# The expected output will be a list of tuples: [(1, 'a'), (1, 'b'), (2, 'a'), (2, 'b')]
print(result)

Question • A5A7

October 21, 2024

What is the output for the Python code below?

def foo():
    try:
        return 1
    finally:
        return 2

k = foo()
print(k)

Answer

2

Let's analyze the code step by step:

def foo():
    # Start of the function 'foo'. This function does not take any arguments.
    try:
        # The 'try' block contains code that may potentially raise an exception.
        return 1
        # The 'return' statement is intended to return the value 1 and exit the function.
        # However, as we'll see in a moment, this will not be the final result.
    finally:
        # The 'finally' block is executed no matter what happens in the 'try' block.
        # It's typically used for clean-up actions but can modify behavior as shown here.
        return 2
        # Here, we have another 'return' statement in the 'finally' block.
        # In Python, the 'finally' block is executed after the 'try' block, 
        # and if a return statement exists here, it will override any return
        # statement in the 'try' block.
        # Therefore, '2' will be the final value returned from the function 'foo'.

k = foo()
# We call the function 'foo' and store its returned value in the variable 'k'.

print(k)
# We print the value of 'k'. Given the behavior outlined above, this will output '2'.

Question • AB52

October 18, 2024

What is the output for the Python code below?

x = (1, 2)
y = x
y += (3, 4)

print(x, y)

Answer

(1, 2) (1, 2, 3, 4)

Let's analyze the code step by step:

# Here, we are defining a tuple 'x' with two elements, 1 and 2.
# A tuple is an immutable sequence type, meaning it cannot be changed after it’s created.
x = (1, 2)

# Now, we're creating a new variable 'y' and setting it equal to 'x'.
# This means 'y' now references the same tuple object in memory that 'x' does.
y = x

# This line uses augmented assignment to concatenate a new tuple (3, 4) to 'y'.
# However, because tuples are immutable, this operation does not modify
# the original tuple that 'y' references. Instead, it creates a new tuple
# by combining the elements of 'y' (which are currently those of 'x') and (3, 4).
# The new tuple (1, 2, 3, 4) gets assigned back to 'y'.
y += (3, 4)

# This print statement outputs the values of 'x' and 'y'.
# Because tuples are immutable, 'x' remains unchanged and still
# references the original tuple (1, 2).
# Meanwhile, 'y' now references the new tuple (1, 2, 3, 4).
print(x, y)

Question • B20E

October 17, 2024

What is the output for the Python code below?

x = {'a': 10, 'b': 20}
y = {'b': 30, 'c': 40}
x.update(y)
print(x)

Answer

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

Let's analyze the code step by step:

# Creating a dictionary `x` with initial key-value pairs
# 'a' is a key with a value of 10, and 'b' is a key with a value of 20
x = {'a': 10, 'b': 20}

# Creating another dictionary `y` with a different set of key-value pairs
# 'b' is a key with a value of 30, and 'c' is a key with a value of 40
y = {'b': 30, 'c': 40}

# The update() method is called on dictionary `x` with `y` as the argument
# The update() method merges the dictionary `y` into `x`
# If there are overlapping keys, the value from dictionary `y` will replace the value in dictionary `x`
# In this case, key 'b' exists in both `x` and `y`
# The value of 'b' in `x` (which is 20) will be replaced by the value in `y` (which is 30)
x.update(y)

# Printing the updated dictionary `x` to see the result after the update
# The print statement will output the final state of `x`
# Expected Output: {'a': 10, 'b': 30, 'c': 40}
# 'a' remains unchanged at 10, 'b' is updated to 30, and 'c' is added with a value of 40
print(x)

Question • E98A

October 16, 2024

What is the output for the Python code below?

from functools import reduce

num = [5, 10, 20]
r = reduce(lambda x, y: x * y, num)
print(r)

Answer

1000

Let's analyze the code step by step:

# `reduce` is a function from the `functools` module which we import here
# `reduce` applies a binary function to the items of a sequence (like a list)
# from left to right in order to reduce the sequence to a single accumulated value.
from functools import reduce

# `num` is a list containing three integer elements: 5, 10, and 20.
num = [5, 10, 20]

# `reduce` function is used here to perform a cumulative operation on the list `num`.
# It takes a lambda function and an iterable (our `num` list) as arguments.
# The lambda function `lambda x, y: x * y` defines an anonymous function that multiplies two numbers.
# Here's how it works: `reduce` will take the first two elements, 5 and 10, multiply them to get 50.
# Then, it will take this result, 50, and multiply it by the next element, 20, to get 1000.
# So, the entire reduction process can be visualized as: 5 * 10 * 20 = 1000.
r = reduce(lambda x, y: x * y, num)

# `print(r)` outputs the result of the `reduce` operation to the console.
# In this case, it will print `1000`, which is the product of all numbers in the list.
print(r)

Question • C340

October 15, 2024

What is the output for the Python code below?

lst = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']
r = lst[-5:-1]
print(r)

Answer

['d', 'e', 'f', 'g']

Let's analyze the code step by step:

# Define a list named 'lst' containing elements from 'a' to 'h'
lst = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']

# Slice the list 'lst' to include elements starting from the 5th last element to the second last element
# Indexing explanation:
# In Python, negative indices are used to specify positions from the end of a list. 
# -1 refers to the last element, -2 to the second last, and so on.
# Hence, `-5` refers to the 5th element from the end, and `-1` refers to the element just before the last one.

# List slicing syntax lst[start:end] fetches elements from 'start' index up to but NOT including the 'end' index.
r = lst[-5:-1]

# Now 'r' will store the sublist from 'lst' which consists of elements:
# Start from index -5: 'd' (since lst[-5] refers to 'd')
# End before index -1: 'g' (since lst[-1] refers to 'h' and is not included)
# Therefore, 'r' will contain ['d', 'e', 'f', 'g']

# Print the sliced list 'r'
print(r)

Question • 90F2

October 14, 2024

What is the output for the Python code below?

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

Answer

KeyError: '🔵'

Let's analyze the code step by step:

# Initialize a set 'c' containing three colored circles Unicode emojis.
# A set is a collection data type in Python that is unordered, mutable, and does not allow duplicate elements.
c = {'🔴', '🟡', '🟢'}

# Try to remove the element '🔵' from the set 'c'.
# The `remove()` method is used to remove a specified element from the set.
# If the specified element is not found in the set, an error (KeyError) will occur.
c.remove('🔵')

# Print the elements of the set 'c'.
# This line will not be executed if a KeyError occurs on the previous line,
# meaning the colored emoji '🔵' does not exist in the set.
print(c)

Question • BAFC

October 11, 2024

What is the output for the Python code below?

from collections import defaultdict

int_dict = defaultdict(int)
int_dict['c'] += 1
result = int_dict['c']

print(result)

Answer

1

Let's analyze the code step by step:

# Importing defaultdict from the collections module
# defaultdict is a subclass of the built-in dict class. 
# It overrides one method and adds one writable instance variable.
from collections import defaultdict

# Creating a defaultdict with int as the default factory function.
# The default factory function is the function that provides the default value for a new key.
# In this case, int() returns 0, so the default value will be 0 for any new key.
int_dict = defaultdict(int)

# Accessing the key 'c' in the int_dict dictionary.
# Since 'c' does not exist in int_dict, defaultdict will call int() to provide a default value of 0.
# Then, the '+=' operation will increment this default value by 1.
int_dict['c'] += 1

# Now, we access the value associated with the key 'c'. After the previous operation,
# the value should now be 1.
result = int_dict['c']

# Print the result to the console. At this point, the program will output the number 1,
# because we've incremented the initial default value of 0 by 1.
print(result)

Question • 8177

October 10, 2024

What is the output for the Python code below?

import numpy as np
a = np.array([1, 2, 3])
b = np.array([4, 5, 6])
c = a + b
print(c)

Answer

[5 7 9]

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])

Question • 4D8B

October 09, 2024

What is the output for the Python code below?

n = [5, 10, 15, 20, 25, 30]
fn = list(filter(lambda x: x > 15, n))
print(fn)

Answer

[20, 25, 30]

Let's analyze the code step by step:

# Define a list of integers
n = [5, 10, 15, 20, 25, 30]

# Use the filter function to create a new list
# The filter function is used to filter out elements from a sequence, in this case, the list 'n'
# It takes two arguments:
# - A function (or a lambda expression) that defines the filtering condition
# - The sequence (here, the list 'n') to filter
fn = list(filter(lambda x: x > 15, n))

# Here's a breakdown of the lambda function:
# - 'lambda x: x > 15' is an anonymous function (lambda function) that takes one argument 'x'
# - It returns True if 'x' is greater than 15, and False otherwise
# - The filter function applies this lambda function to each element in the list 'n'
# - Only elements for which the lambda function returns True are included in the result

# Convert the filter object to a list
# Note: The filter function returns a filter object, which is an iterator.
# To get a list of the results, we convert it using the list() function.

# Print the filtered list
print(fn)

# Expected Output:
# The list 'n' contains elements 5, 10, 15, 20, 25, 30.
# The lambda function filters out elements <= 15.
# Therefore, the filtered list 'fn' will contain only elements > 15: [20, 25, 30]