Reputation: 31
I created a list with random letters(uppercase & lowercase). Im trying to write code so it only print the unique values considering the uppercase & lowercase. for example, ["A","a","a","B","b"] would print ["a","b"]
heres my code so far:
List_1 = ["a","a","a","b","A","b", "B", "c", "C"]
for x in List_1:
l = x.lower()
myset = set(l)
print(myset)
& here is the output:
{'a'}
{'a'}
{'a'}
{'b'}
{'a'}
{'b'}
{'b'}
{'c'}
{'c'}
Now that im printing these value through a set, why is it still printing duplicate values? what am I doing wrong?
Upvotes: 2
Views: 95
Reputation: 4799
You're taking every single element in the list, then making a set with that - each set has no knowledge of the other set.
Try something like this:
myset = set(l.lower() for l in List_1)
You'll end up with a true set.
Upvotes: 4
Reputation: 545528
Your current solution iterates over the list and creates a singleton set for each item in the list, which it then prints and throws away.
To convert a list to a set, simply write set(the_list)
.
In your case, you first want to transform the list (by lower-casing the letters). This can be done via list comprehension, which creates a new list. Or you could use a generator expression, which can be directly passed to the set
constructor without first creating a temporary list:
result = set(s.lower() for s in the_list)
And lastly, Python has special syntactic sugar for this construct, using set comprehension, which is shown in mkrieger1’s answer.
Upvotes: 1
Reputation: 23151
You are doing wrong that you create a new set in each loop iteration.
Instead of
myset = set(l)
you want to use
myset.add(l)
and initialize myset = set()
before the loop.
Alternatively, you can replace the whole loop by a set comprehension:
myset = {x.lower() for x in List_1}
Upvotes: 6