PT0-002 · Question #513
A penetration tester is troubleshooting the right value for the urls variable that should be used in the following script: Which of the following instructions in a Python script will prevent…
The correct answer is B. list({u: True for u in url_list}.keys()). To remove duplicate entries from a list in Python, converting the list to a dictionary and then extracting the keys is an efficient method.
Question
A penetration tester is troubleshooting the right value for the urls variable that should be used in the following script:
Which of the following instructions in a Python script will prevent duplicate entries in the output and work with the script above?
Exhibit
Options
- A[u for u in url_list if u not in url_list]
- Blist({u: True for u in url_list}.keys())
- Cf"{u: True for u in url_list}"
- Djson.dumps({u: True for u in url_list}.keys())
How the community answered
(64 responses)- A5% (3)
- B70% (45)
- C17% (11)
- D8% (5)
Why each option
To remove duplicate entries from a list in Python, converting the list to a dictionary and then extracting the keys is an efficient method.
`[u for u in url_list if u not in url_list]` is a logically flawed list comprehension that will always result in an empty list because an item is always in the list it is being iterated over.
Creating a dictionary `{{u: True for u in url_list}}` uses each unique URL as a key, automatically eliminating duplicates since dictionary keys must be unique. Subsequently, calling `.keys()` returns a view object of these unique URLs, and `list()` converts this view into a list of unique entries suitable for further processing.
`f"{{u: True for u in url_list}}"` is an f-string that attempts to format the dictionary as a string, not create a list of unique URLs.
`json.dumps({{u: True for u in url_list}}.keys())` converts the keys (unique URLs) into a JSON formatted string, which is not the desired list output.
Concept tested: Python list deduplication using dictionary keys
Source: https://docs.python.org/3/tutorial/datastructures.html#dictionaries
Topics
Community Discussion
No community discussion yet for this question.
