How can I convert this "for-loop" below to "list-comprehension? I want to create a list of non-repetitive elements from repetitive-elemets list.
many_colors = ['red', 'red', 'blue', 'black', 'blue']
colors = []
for c in many_colors:
if not c in colors:
colors.append(c)
# colors = ['red', 'blue', 'black']
I tried this (below) but error occurs that colors are not defined.
colors = [c for c in many_colors if not c in colors]
You can use set
in python which represents an unordered collection of unique elements.
Use:
colors = list(set(many_colors))
print(colors)
This prints:
['red', 'black', 'blue']