0
0
Pythonprogramming~10 mins

Lambda with sorted() in Python - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to sort the list of numbers in ascending order using sorted() with a lambda that returns the number itself.

Python
numbers = [5, 2, 9, 1]
sorted_numbers = sorted(numbers, key=lambda x: [1])
print(sorted_numbers)
Drag options to blanks, or click blank then click option'
Alen(x)
Bx
Cx*2
Dx+1
Attempts:
3 left
๐Ÿ’ก Hint
Common Mistakes
Using len(x) causes an error because numbers are integers, not sequences.
Using x*2 or x+1 changes the sorting order incorrectly.
2fill in blank
medium

Complete the code to sort the list of words by their length using sorted() and a lambda.

Python
words = ['apple', 'fig', 'banana', 'kiwi']
sorted_words = sorted(words, key=lambda w: [1])
print(sorted_words)
Drag options to blanks, or click blank then click option'
Aw[0]
Bw.upper()
Clen(w)
Dw[::-1]
Attempts:
3 left
๐Ÿ’ก Hint
Common Mistakes
Using w[0] sorts by first letter, not length.
Using w.upper() sorts alphabetically ignoring case.
Using w[::-1] sorts by reversed word, not length.
3fill in blank
hard

Fix the error in the code to sort a list of tuples by the second element using sorted() and a lambda.

Python
pairs = [(1, 3), (2, 1), (3, 2)]
sorted_pairs = sorted(pairs, key=lambda x: [1])
print(sorted_pairs)
Drag options to blanks, or click blank then click option'
Ax[1]
Bx[0]
Cx[2]
Dx
Attempts:
3 left
๐Ÿ’ก Hint
Common Mistakes
Using x[0] sorts by the first element, not the second.
Using x[2] causes an IndexError because tuples have only two elements.
Using x sorts by the whole tuple, which sorts by first element then second.
4fill in blank
hard

Fill both blanks to create a dictionary of words and their lengths, but only include words longer than 3 characters.

Python
words = ['cat', 'elephant', 'dog', 'lion']
lengths = {word: [1] for word in words if [2]
print(lengths)
Drag options to blanks, or click blank then click option'
Alen(word)
Bword > 3
Clen(word) > 3
Dword
Attempts:
3 left
๐Ÿ’ก Hint
Common Mistakes
Using word > 3 compares a string to a number, causing an error.
Using word alone in the condition includes all words.
Using len(word) without a comparison includes all words.
5fill in blank
hard

Fill all three blanks to create a dictionary with uppercase words as keys and their lengths as values, including only words with length greater than 4.

Python
words = ['tree', 'mountain', 'river', 'sky']
result = [1]: [2] for w in words if [3]
print(result)
Drag options to blanks, or click blank then click option'
Aw.upper()
Blen(w)
Clen(w) > 4
Dw.lower()
Attempts:
3 left
๐Ÿ’ก Hint
Common Mistakes
Using w.lower() for keys instead of uppercase.
Not filtering words by length.
Using w instead of w.upper() for keys.