15. Remove duplicates
Write a function unique(items) that takes a list and returns a new list with each item only once. Keep the items in
the order they first appear: when an item repeats, keep its first appearance and drop the later ones.
Items can be numbers or strings, mixed in one list. A number and a string are different items, even when they look
alike: 7 and "7" both stay. If items is empty, return an empty list [].
Example 1
items = [3, 1, 3, 2, 1][3, 1, 2]Example 2
items = ["b", "a", "b"]["b", "a"]Example 3
items = [7, "7", 7][7, "7"]Constraints
itemshas 0 to 100 items.- Each item is a whole number or a string.
Submit also runs 4 more tests you can't see.
Practises Sets (lesson 12).
list(set(items))removes the repeats but loses the order, so it can't be the whole answer.- Build a new list as you go through
items, and add an item to it only the first time you see it. - Keep a set of the items seen so far:
item in seenis a fast check andseen.add(item)remembers one.7and"7"are different items, so both stay.
Solve it without hints for 3 stars, with hints for 2, after seeing the solution for 1.
One way to solve it, once you've had a go.
Solving it after seeing the solution earns 1 star.
Your Submits show here, with their code, so you can go back to one. They stay in this browser.
def unique(items):
"""Remove repeats, keeping each item's first place.
items: list of int or str; may be empty
Returns: list, each item once, in first-seen order
"""
# Write your code here
pass
Run your code to see how it does on the test cases, or Submit to check every test.