+ 3

Sets in Python Challenge

Once again, I come across incorrect questions in the Python Challenge related to sets. e.g. What is output of this code? x = {1:0, 0:1} y = [1, [4, 6, 5, 4], 2] print(list(set(y[x[0]]))[1]) Set is an unordered and unindexed collection of items in Python. The order of elements in a set is not guaranteed and may differ from the order of the original list. Therefore, when converting a set back to a list using list(), the order of elements can be any valid order, but it is guaranteed to be without duplicates. In this case, when converting the list [4, 6, 5, 4] to a set, the duplicate element 4 will be removed, leaving only the unique elements [4, 6, 5]. When converting it back to a list, the possible variations of the answer could be: [4, 5, 6] [4, 6, 5] [5, 4, 6] [5, 6, 4] [6, 4, 5] [6, 5, 4] These are just some of the possible variations, as the order of elements in a set can be arbitrary.

18th Jun 2023, 8:47 PM
Alexey Kopyshev
Alexey Kopyshev - avatar
3 Antworten
+ 2
you are right. Although you might get consistent result in this example, there is no guarantee in the order with sets. It misleads the student to expect a predictable result in the indexing from unsorted lists constructed from sets.
18th Jun 2023, 11:11 PM
Bob_Li
Bob_Li - avatar
0
x is a dictionary. Orin Cook, you need glasses... 😁.
19th Jun 2023, 5:50 AM
Bob_Li
Bob_Li - avatar
0
Oops lol, maybe I do
19th Jun 2023, 5:57 AM
Orin Cook
Orin Cook - avatar