nerdexam
CompTIA

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.

Tools and Code Analysis

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

PT0-002 question #513 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)
  • A
    5% (3)
  • B
    70% (45)
  • C
    17% (11)
  • D
    8% (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.

A[u for u in url_list if u not in url_list]

`[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.

Blist({u: True for u in url_list}.keys())Correct

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.

Cf"{u: True for u in url_list}"

`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.

Djson.dumps({u: True for u in url_list}.keys())

`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

#Python Scripting#Data Manipulation#Duplicate Removal#Dictionary Comprehension

Community Discussion

No community discussion yet for this question.

Full PT0-002 Practice