Quiz: Output Exercise
Instructions
- Read the code snippet carefully.
- Try to calculate the output in your mind or on paper.
- Click on the "Answer" dropdown to check your solution.
- If you need more clarification, click on the "Explanation" dropdown.
- What is the output of the given code below:
x = 5
y = 2
print(x + y)
Answer
7
Explanation
The code adds the values of x
(5) and y
(2), resulting in 7, which is then printed.
- What is the output of the given code below:
text = "Python"
print(text * 3)
Answer
PythonPythonPython
Explanation
The *
operator with a string and an integer repeats the string that many times. Here, "Python" is repeated 3 times.
- What is the output of the given code below:
x = 10
y = 3
print(x // y)
Answer
3
Explanation
The //
operator performs integer division (floor division). 10 divided by 3 is 3 with a remainder, but floor division rounds down to the nearest integer, which is 3.
- What is the output of the given code below:
x = 5
x += 3
print(x)
Answer
8
Explanation
The +=
operator adds the right operand to the left operand and assigns the result to the left operand. So, x += 3
is equivalent to x = x + 3
, which results in 8.
- What is the output of the given code below:
print(bool(0), bool(1), bool(""))
Answer
False True False
Explanation
In Python, 0
and empty strings are considered falsy values, while any non-zero number is truthy. Therefore, bool(0)
is False
, bool(1)
is True
, and bool("")
is False
.
- What is the output of the given code below:
x = [1, 2, 3]
y = x
y.append(4)
print(x)
Answer
[1, 2, 3, 4]
Explanation
Lists are mutable and assigned by reference. When y = x
is executed, both x
and y
refer to the same list. So, when 4 is appended to y
, it's also reflected in x
.
- What is the output of the given code below:
x = "Hello"
y = "World"
print(x[1] + y[1])
Answer
eo
Explanation
String indexing starts at 0. x[1]
is 'e' (the second character of "Hello"), and y[1]
is 'o' (the second character of "World"). The +
operator concatenates these characters.
- What is the output of the given code below:
x = 5
y = 2
print(x % y)
Answer
1
Explanation
The %
operator calculates the remainder of division. 5 divided by 2 is 2 with a remainder of 1, so 5 % 2 equals 1.
- What is the output of the given code below:
x = [1, 2, 3]
print(len(x) + x[1])
Answer
5
Explanation
len(x)
returns 3 (the length of the list), and x[1]
is 2 (the second element of the list). The code adds these values: 3 + 2 = 5.
- What is the output of the given code below:
x = "Python"
print(x[::-1])
Answer
nohtyP
Explanation
The slice notation [::-1]
reverses the string. It starts from the end (no start index), goes to the beginning (no stop index), and moves with a step of -1 (backwards).
- What is the output of the given code below:
x = 10
y = 3
print(x % y * 2)
Answer
2
Explanation
First, x % y
is calculated: 10 % 3 = 1 (the remainder of 10 divided by 3). Then, this result is multiplied by 2: 1 * 2 = 2.
- What is the output of the given code below:
x = [1, 2, 3]
y = x.copy()
y.append(4)
print(x)
Answer
[1, 2, 3]
Explanation
Unlike the previous list example, y = x.copy()
creates a new list with the same elements as x
. Modifying y
doesn't affect x
, so x
remains unchanged.
- What is the output of the given code below:
x = "Hello"
print(x.replace("l", "L", 1))
Answer
HeLlo
Explanation
The replace()
method replaces occurrences of a substring with another substring. The third argument (1) limits it to replacing only the first occurrence of "l" with "L".
- What is the output of the given code below:
x = [1, 2, 3, 4, 5]
print(x[1:4:2])
Answer
[2, 4]
Explanation
The slice [1:4:2]
starts at index 1, goes up to (but not including) index 4, and uses a step of 2. This results in selecting elements at indices 1 and 3.
- What is the output of the given code below:
x = "Python"
y = "Programming"
print(x[0] + y[-1])
Answer
Pg
Explanation
x[0]
is 'P' (the first character of "Python"), and y[-1]
is 'g' (the last character of "Programming"). These are concatenated to form "Pg".
- What is the output of the given code below:
x = 5
y = 2
print(x ** y)
Answer
25
Explanation
The **
operator performs exponentiation. This code calculates 5 raised to the power of 2, which is 25.
- What is the output of the given code below:
x = [1, 2, 3]
y = [4, 5, 6]
print(x + y)
Answer
[1, 2, 3, 4, 5, 6]
Explanation
When used with lists, the +
operator concatenates them, creating a new list containing all elements from both lists in the order they appear.
- What is the output of the given code below:
x = "Hello"
print(x.find("l"))
Answer
2
Explanation
The find()
method returns the index of the first occurrence of the substring. In "Hello", the first 'l' is at index 2 (remember, indexing starts at 0).
- What is the output of the given code below:
x = [1, 2, 3, 2, 1]
print(x.count(2))
Answer
2
Explanation
The count()
method returns the number of occurrences of an element in the list. The number 2 appears twice in the list, so the output is 2.
- What is the output of the given code below:
x = "Python"
print(x.lower().upper())
Answer
PYTHON
Explanation
First, lower()
converts the string to lowercase ("python"), then upper()
converts it to uppercase ("PYTHON"). The final result is "PYTHON".
- What is the output of the given code below:
x = [1, 2, 3]
x.extend([4, 5])
print(len(x))
Answer
5
Explanation
The extend()
method adds all elements of the given list to the end of the original list. After extending, x
becomes [1, 2, 3, 4, 5]
, which has a length of 5.
- What is the output of the given code below:
x = "Hello, World!"
print(x.split(","))
Answer
['Hello', ' World!']
Explanation
The split()
method splits a string into a list of substrings based on the specified delimiter. Here, it splits at the comma, resulting in two elements.
- What is the output of the given code below:
x = 5
y = 2
print(f"{x} divided by {y} is {x/y:.2f}")
Answer
5 divided by 2 is 2.50
Explanation
This uses an f-string for formatting. {x/y:.2f}
formats the result of 5/2 to two decimal places. The .2f
specifies two digits after the decimal point.
- What is the output of the given code below:
x = [1, 2, 3, 4, 5]
print(sum(x[1::2]))
Answer
9
Explanation
The slice [1::2]
starts at index 1 and takes every second element, resulting in [2, 4]
. The sum()
function then adds these numbers: 2 + 4 = 6.
- What is the output of the given code below:
x = "Python"
y = "Java"
print(sorted(x + y))
Answer
[' ', 'a', 'h', 'J', 'n', 'o', 'P', 't', 'v', 'y']
Explanation
The sorted()
function returns a new sorted list of the given iterable. Here, it concatenates "Python" and "Java", then sorts all characters alphabetically (with uppercase letters coming before lowercase).
- What is the output of the given code below:
x = "Hello"
print(x.center(10, "*"))
Answer
Hello*
Explanation
The center()
method centers the string within a string of specified length. Here, it centers "Hello" in a 10-character string, filling the extra space with asterisks.
- What is the output of the given code below:
x = [1, 2, 3, 4, 5]
print(x[-2:] + x[:2])
Answer
[4, 5, 1, 2]
Explanation
x[-2:]
slices the last two elements [4, 5], and x[:2]
slices the first two elements [1, 2]. These are then concatenated.
- What is the output of the given code below:
x = 5
y = 2
print(f"{x} to the power of {y} is {x**y}")
Answer
5 to the power of 2 is 25
Explanation
This uses an f-string for formatting. {x**y}
calculates 5 raised to the power of 2, which is 25.
- What is the output of the given code below:
x = [1, 2, 3]
y = [4, 5, 6]
print(list(zip(x, y)))
Answer
[(1, 4), (2, 5), (3, 6)]
Explanation
The zip()
function pairs elements from the two lists. list()
converts the zip object to a list of tuples.
- What is the output of the given code below:
x = "Python"
print(x.ljust(10, '-') + x.rjust(10, '-'))
Answer
Python---- ----Python
Explanation
ljust()
left-justifies the string in a 10-character field, filling with '-'. rjust()
does the same but right-justifies. These are then concatenated.
- What is the output of the given code below:
x = [1, 2, 3, 4, 5]
print(x[::2])
Answer
[1, 3, 5]
Explanation
The slice [::2]
starts at the beginning, goes to the end, and takes every second element.
- What is the output of the given code below:
x = "Hello"
y = "World"
print(f"{x:>10}{y:<10}")
Answer
HelloWorld
Explanation
In the f-string, :>10
right-aligns "Hello" in a 10-character field, while :<10
left-aligns "World" in a 10-character field.
- What is the output of the given code below:
x = [1, 2, 3, 4, 5]
print(sum(x[1::2]) - sum(x[::2]))
Answer
-3
Explanation
x[1::2]
is [2, 4], summing to 6. x[::2]
is [1, 3, 5], summing to 9. 6 - 9 = -3.
- What is the output of the given code below:
x = "Python"
print(''.join(sorted(set(x.lower()))))
Answer
hnopty
Explanation
set(x.lower())
creates a set of unique lowercase letters. sorted()
orders them alphabetically. ''.join()
combines them into a string.
- What is the output of the given code below:
x = [1, 2, 3]
y = [i*2 for i in x]
print(y)
Answer
[2, 4, 6]
Explanation
This is a list comprehension. It creates a new list y
where each element is twice the corresponding element in x
.
- What is the output of the given code below:
x = "Hello World"
print(x.swapcase())
Answer
hELLO wORLD
Explanation
The swapcase()
method swaps the case of each character: uppercase becomes lowercase and vice versa.
- What is the output of the given code below:
x = [1, 2, 3, 4, 5]
print(x.pop(2))
print(x)
Answer
3 [1, 2, 4, 5]
Explanation
pop(2)
removes and returns the element at index 2 (which is 3). Then the modified list is printed.
- What is the output of the given code below:
x = "Python"
print(x.encode())
Answer
b'Python'
Explanation
The encode()
method returns a bytes object. The 'b' prefix indicates it's a bytes literal.
- What is the output of the given code below:
x = [1, 2, 3]
y = [4, 5, 6]
z = list(map(lambda a, b: a+b, x, y))
print(z)
Answer
[5, 7, 9]
Explanation
map()
applies the lambda function (which adds two numbers) to each pair of elements from x
and y
. The result is converted to a list.
- What is the output of the given code below:
x = "Hello"
y = reversed(x)
print(''.join(y))
Answer
olleH
Explanation
reversed()
returns an iterator that accesses the string's characters in reverse order. ''.join()
combines these characters into a string.
- What is the output of the given code below:
x = [1, 2, 3, 4, 5]
print(x[:-1])
Answer
[1, 2, 3, 4]
Explanation
The slice [:-1]
returns all elements of the list except the last one.
- What is the output of the given code below:
x = "Python"
print(x.startswith("Py"))
Answer
True
Explanation
The startswith()
method returns True
if the string starts with the specified substring, which it does in this case.
- What is the output of the given code below:
x = [1, 2, 3, 4, 5]
y = filter(lambda a: a % 2 == 0, x)
print(list(y))
Answer
[2, 4]
Explanation
filter()
applies the lambda function to each element of x
, keeping only those for which the function returns True
(even numbers in this case).
- What is the output of the given code below:
x = "Hello"
y = "World"
print(min(x, y))
Answer
Hello
Explanation
When min()
is used with strings, it returns the lexicographically smaller string. "Hello" comes before "World" alphabetically.
- What is the output of the given code below:
x = [1, 2, 3]
y = x * 2
print(y)
Answer
[1, 2, 3, 1, 2, 3]
Explanation
The *
operator with a list and an integer repeats the list that many times.
- What is the output of the given code below:
x = "Python Programming"
print(x.count('P'))
Answer
2
Explanation
The count()
method returns the number of occurrences of a substring in the string. 'P' appears twice in "Python Programming".
- What is the output of the given code below:
x = [1, 2, 3, 4, 5]
print(sum(x[1:-1]))
Answer
9
Explanation
The slice [1:-1]
selects all elements except the first and last, resulting in [2, 3, 4]. The sum()
function then adds these numbers: 2 + 3 + 4 = 9.
- What is the output of the given code below:
x = "Python"
print(''.join(reversed(sorted(x))))
Answer
ytohnP
Explanation
First, sorted(x)
orders the characters alphabetically. Then reversed()
reverses this order. Finally, ''.join()
combines the characters into a string.
- What is the output of the given code below:
x = [1, 2, 3, 4, 5]
print(x[::2] + x[1::2])
Answer
[1, 3, 5, 2, 4]
Explanation
x[::2]
selects every second element starting from the first: [1, 3, 5]. x[1::2]
selects every second element starting from the second: [2, 4]. These are then concatenated.
- What is the output of the given code below:
x = "Hello World"
print(x.replace(" ", "").isalpha())
Answer
True
Explanation
First, replace(" ", "")
removes the space. Then isalpha()
checks if all characters in the string are alphabetic, which they are after removing the space.
- What is the output of the given code below:
x = [1, 2, 3, 4, 5]
print(x[::-2])
Answer
[5, 3, 1]
Explanation
The slice [::-2]
starts from the end, moves towards the beginning, and takes every second element.
- What is the output of the given code below:
x = "Python"
print(x.rjust(10, '*'))
Answer
****Python
Explanation
The rjust()
method right-justifies the string in a field of width 10, filling the left side with asterisks.
- What is the output of the given code below:
x = [1, 2, 3]
y = [4, 5, 6]
print(list(map(pow, x, y)))
Answer
[1, 32, 729]
Explanation
map(pow, x, y)
applies the pow()
function to each pair of elements from x
and y
. So it calculates 1^4, 2^5, and 3^6.
- What is the output of the given code below:
x = "Hello World"
print(x[::2])
Answer
HloWrd
Explanation
The slice [::2]
selects every second character from the string, starting from the first character.
- What is the output of the given code below:
x = [1, 2, 3, 4, 5]
print(x.index(3))
Answer
2
Explanation
The index()
method returns the index of the first occurrence of the specified element in the list. The number 3 is at index 2 in the list.
- What is the output of the given code below:
x = "Python"
print(''.join([i*2 for i in x]))
Answer
PPyytthhoonn
Explanation
This list comprehension doubles each character in the string. Then ''.join()
combines these doubled characters into a single string.
- What is the output of the given code below:
x = [1, 2, 3, 4, 5]
print(x[-3:] + x[:-3])
Answer
[3, 4, 5, 1, 2]
Explanation
x[-3:]
selects the last three elements [3, 4, 5], and x[:-3]
selects all but the last three elements [1, 2]. These are then concatenated.
- What is the output of the given code below:
x = "Python"
print(x.zfill(10))
Answer
0000Python
Explanation
The zfill()
method pads the string on the left with zeros to fill the specified width.
- What is the output of the given code below:
x = [1, 2, 3, 4, 5]
print(sum(filter(lambda a: a % 2 != 0, x)))
Answer
9
Explanation
filter()
keeps only the odd numbers [1, 3, 5], and then sum()
adds them up: 1 + 3 + 5 = 9.
- What is the output of the given code below:
x = "Hello"
y = "World"
print(sorted(x + y))
Answer
[' ', 'd', 'e', 'H', 'l', 'l', 'l', 'o', 'o', 'r', 'W']
Explanation
The strings are concatenated, then sorted()
returns a list of all characters in alphabetical order. Note that uppercase letters come before lowercase in ASCII ordering.
- What is the output of the given code below:
x = [1, 2, 3]
print(list(enumerate(x, start=10)))
Answer
[(10, 1), (11, 2), (12, 3)]
Explanation
enumerate()
creates pairs of indices and values. The start
parameter sets the initial index to 10.
- What is the output of the given code below:
x = "Python Programming"
print(x.partition("on"))
Answer
('Pyth', 'on', ' Programming')
Explanation
The partition()
method splits the string at the first occurrence of the specified substring, returning a tuple of the part before the separator, the separator itself, and the part after the separator.
- What is the output of the given code below:
x = [1, 2, 3, 4, 5]
print(x[1:4][::-1])
Answer
[4, 3, 2]
Explanation
First, x[1:4]
selects [2, 3, 4]. Then [::-1]
reverses this selection.
- What is the output of the given code below:
x = "Hello World"
print(x.strip('Held'))
Answer
o Wor
Explanation
The strip()
method removes the specified characters from the beginning and end of the string. It removes 'H' from the start and 'ld' from the end.
- What is the output of the given code below:
x = [1, 2, 3]
y = [4, 5, 6]
print([a*b for a, b in zip(x, y)])
Answer
[4, 10, 18]
Explanation
This list comprehension multiplies corresponding elements from x
and y
: 14, 25, 3*6.
- What is the output of the given code below:
x = "Python"
print(x.ljust(10, '*').rjust(15, '-'))
Answer
-----Python****
Explanation
First, ljust(10, '*')
pads the right side to width 10 with '*'. Then rjust(15, '-')
pads the left side of the result to width 15 with '-'.
- What is the output of the given code below:
x = [1, 2, 3, 4, 5]
print(x[::2] * 2)
Answer
[1, 3, 5, 1, 3, 5]
Explanation
x[::2]
selects every second element [1, 3, 5], then * 2
repeats this list twice.
- What is the output of the given code below:
x = "Python"
print(''.join(sorted(x, key=str.lower)))
Answer
hnoPty
Explanation
sorted()
with key=str.lower
sorts the characters alphabetically, ignoring case. ''.join()
then combines them into a string.
- What is the output of the given code below:
x = [1, 2, 3, 4, 5]
print(list(map(lambda a: a**2 if a % 2 == 0 else a, x)))
Answer
[1, 4, 3, 16, 5]
Explanation
This map()
applies a lambda function that squares even numbers and leaves odd numbers unchanged.
- What is the output of the given code below:
x = "Hello World"
print(x.translate(str.maketrans("o", "0")))
Answer
Hell0 W0rld
Explanation
str.maketrans()
creates a translation table that replaces "o" with "0". translate()
then applies this translation to the string.
- What is the output of the given code below:
x = [1, 2, 3, 4, 5]
print([i if i % 2 == 0 else i*2 for i in x])
Answer
[2, 2, 6, 4, 10]
Explanation
This list comprehension doubles odd numbers and leaves even numbers unchanged.
- What is the output of the given code below:
x = "Python"
print(x.center(10, '*')[1:-1])
Answer
*Python
Explanation
center(10, '*')
creates 'Python'. Then [1:-1]
slices off the first and last characters.
- What is the output of the given code below:
x = [1, 2, 3, 4, 5]
print(list(reversed(x[1::2])))
Answer
[5, 3]
Explanation
x[1::2]
selects every second element starting from index 1: [2, 4]. reversed()
then reverses this list.
- What is the output of the given code below:
x = "Hello World"
print(x.swapcase().title())
Answer
Hello World
Explanation
swapcase()
changes "Hello World" to "hELLO wORLD". Then title()
capitalizes the first letter of each word.
- What is the output of the given code below:
x = [1, 2, 3, 4, 5]
print(sum(x[1::2]) / len(x[::2]))
Answer
2.0
Explanation
sum(x[1::2])
sums every second element starting from index 1: 2 + 4 = 6. len(x[::2])
counts every second element starting from index 0: [1, 3, 5], which is 3. So, 6 / 3 = 2.0.
- What is the output of the given code below:
x = "Python Programming"
print(x.replace('P', 'J', 1).replace('P', 'j', 1))
Answer
Jython jrogramming
Explanation
The first replace()
changes the first 'P' to 'J'. The second replace()
changes the next 'P' to 'j'.
- What is the output of the given code below:
x = [1, 2, 3, 4, 5]
y = [6, 7, 8, 9, 10]
print([a if a % 2 == 0 else b for a, b in zip(x, y)])
Answer
[6, 2, 8, 4, 10]
Explanation
This list comprehension selects the element from x
if it's even, otherwise it selects the corresponding element from y
.
- What is the output of the given code below:
x = "Python"
print(''.join(x[i] for i in range(len(x)-1, -1, -2)))
Answer
nhy
Explanation
This generator expression selects characters from the end of the string, moving backwards by 2 each time. ''.join()
combines these characters into a string.
- What is the output of the given code below:
x = [1, 2, 3, 4, 5]
print(list(filter(lambda a: a > sum(x)/len(x), x)))
Answer
[4, 5]
Explanation
sum(x)/len(x)
calculates the average of x
, which is 3. The filter()
function then keeps only the numbers greater than 3.
- What is the output of the given code below:
x = "Hello World"
print(x.encode('ascii').decode('ascii'))
Answer
Hello World
Explanation
encode('ascii')
converts the string to ASCII bytes, then decode('ascii')
converts it back to a string. Since all characters are ASCII, the string remains unchanged.
- What is the output of the given code below:
x = [1, 2, 3, 4, 5]
print(list(map(lambda a: a**2, filter(lambda a: a % 2 != 0, x))))
Answer
[1, 9, 25]
Explanation
First, filter()
selects odd numbers [1, 3, 5]. Then map()
applies the square function to each of these numbers.
- What is the output of the given code below:
x = "Python"
print(''.join(sorted(set(x.lower()), key=x.lower().index)))
Answer
python
Explanation
This creates a set of unique lowercase letters, then sorts them based on their first appearance in the original (lowercase) string.
- What is the output of the given code below:
x = [1, 2, 3, 4, 5]
print(sum(i for i in x if i % 2 == 0) - sum(i for i in x if i % 2 != 0))
Answer
-3
Explanation
This calculates the sum of even numbers (2 + 4 = 6) minus the sum of odd numbers (1 + 3 + 5 = 9), resulting in 6 - 9 = -3.
- What is the output of the given code below:
x = "Hello World"
print(x.translate(str.maketrans("aeiou", "12345")))
Answer
H2ll4 W4rld
Explanation
str.maketrans()
creates a translation table that replaces vowels with numbers. translate()
then applies this translation to the string.
- What is the output of the given code below:
x = [1, 2, 3, 4, 5]
print([i if i < 3 else i*2 for i in x])
Answer
[1, 2, 6, 8, 10]
Explanation
This list comprehension doubles numbers greater than or equal to 3, and leaves other numbers unchanged.
- What is the output of the given code below:
x = "Python Programming"
print(x.lower().count('p'))
Answer
2
Explanation
First, lower()
converts the string to lowercase. Then count('p')
counts the occurrences of 'p', which appear twice in "python programming".
- What is the output of the given code below:
x = [1, 2, 3, 4, 5]
print(list(zip(x[::2], x[1::2])))
Answer
[(1, 2), (3, 4), (5, None)]
Explanation
x[::2]
is [1, 3, 5] and x[1::2]
is [2, 4]. zip()
pairs these up, adding None when one list runs out of elements.
- What is the output of the given code below:
x = "Hello"
y = "World"
print(''.join(a+b for a, b in zip(x, y)))
Answer
HWeolrllod
Explanation
This generator expression pairs up characters from x
and y
, concatenates each pair, and then ''.join()
combines all these pairs into a single string.
- What is the output of the given code below:
x = [1, 2, 3, 4, 5]
print(max(x) - min(x[1::2]))
Answer
3
Explanation
max(x)
is 5. x[1::2]
is [2, 4], so min(x[1::2])
is 2. The difference is 5 - 2 = 3.
- What is the output of the given code below:
x = "Python"
print(''.join(chr(ord(c) + 1) for c in x))
Answer
Qzuipo
Explanation
This generator expression converts each character to its ASCII value (ord()
), adds 1, then converts back to a character (chr()
). This effectively shifts each letter to the next one in the alphabet.
- What is the output of the given code below:
x = [1, 2, 3, 4, 5]
print(list(map(lambda a, b: a*b, x, x[::-1])))
Answer
[5, 8, 9, 8, 5]
Explanation
This map()
multiplies each element of x
with the corresponding element of x
reversed. So it computes [15, 24, 33, 42, 5*1].
- What is the output of the given code below:
x = "Hello World"
print(x.replace(' ', '').isalnum())
Answer
True
Explanation
First, replace(' ', '')
removes the space. Then isalnum()
checks if all characters in the string are alphanumeric, which they are after removing the space.
- What is the output of the given code below:
x = [1, 2, 3, 4, 5]
print([sum(x[:i+1]) for i in range(len(x))])
Answer
[1, 3, 6, 10, 15]
Explanation
This list comprehension calculates the cumulative sum of the list. For each index, it sums all elements up to and including that index.
- What is the output of the given code below:
x = "Python"
print(''.join(sorted(x * 2, key=lambda c: (c.lower(), c.isupper()))))
Answer
hhnnoooPPttyy
Explanation
This sorts the characters of "PythonPython" first by lowercase value, then by whether they're uppercase. This groups lowercase before uppercase for each letter.
- What is the output of the given code below:
x = [1, 2, 3, 4, 5]
print(list(filter(lambda a: a == len(x) or x.index(a) == a-1, x)))
Answer
[1, 5]
Explanation
This filter()
keeps elements that are either equal to the length of the list (5) or whose value minus 1 equals their index. This is true for 1 (index 0) and 5 (length of list).
- What is the output of the given code below:
x = "Hello World"
print(''.join(c.lower() if i % 2 else c.upper() for i, c in enumerate(x)))
Answer
HeLlO WoRlD
Explanation
This generator expression alternates between uppercase and lowercase for each character based on its index.
- What is the output of the given code below:
x = [1, 2, 3, 4, 5]
print(sum(map(lambda a, b: a*b, x, range(len(x)))))
Answer
40
Explanation
This map()
multiplies each element of x
with its index (0 to 4), resulting in [10, 21, 32, 43, 5*4]. The sum()
function then adds these values: 0 + 2 + 6 + 12 + 20 = 40.
- What is the output of the given code below:
x = "Python"
print(''.join(c * (i+1) for i, c in enumerate(x)))
Answer
Pyythhhoooonnn
Explanation
This generator expression repeats each character a number of times equal to its index plus one. So 'P' is repeated once, 'y' twice, 't' three times, and so on.
- What is the output of the given code below:
x = [1, 2, 3, 4, 5]
print(list(accumulate(x)))
Answer
[1, 3, 6, 10, 15]
Explanation
The accumulate()
function from the itertools
module (which is assumed to be imported) calculates the cumulative sum of the list.
- What is the output of the given code below:
x = "Python Programming"
print(len(set(x.lower())))
Answer
13
Explanation
This code first converts the string to lowercase, then creates a set of unique characters. The length of this set is the number of unique characters in the string (including the space).