0

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]

3 Answers3

0

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']
Shubham Sharma
  • 52,812
  • 6
  • 20
  • 45
-1

Use a set to make your life easier:

colors = [c for c in set(many_colors)]
jfaccioni
  • 6,606
  • 1
  • 8
  • 23
-1

colors only exists after the completion of the comprehension. A comprehension might not even be optimal. You can do

colors = list(set(colors))

And if you want to keep the order of occurrence:

from collections import OrderedDict

colors = list(OrderedDict.fromkeys(many_colors))
user2390182
  • 67,685
  • 6
  • 55
  • 77