1

I would like to make the for... if in the following code into one line:

cities = ["Berlin", "Berlin", "Berlin", "London"]

unique_cities = []

for city in cities:
    if city not in unique_cities:
        unique_cities.append(c)

print unique_cities

I imagine something like this:

unique_cities = [city for city in cities if city not in unique_cities]

which of course doesn't work because unique_cities is not defined in that loop.

How would I make a one-liner out of this?

Juicy
  • 10,990
  • 33
  • 107
  • 196

2 Answers2

1

If order is not important, the easier way to accomplish this is just

unique_cities = list(set(cities))
Cory Kramer
  • 107,498
  • 14
  • 145
  • 201
1

I think it would be easier to turn it into a set:

unique_cities = set(cities)
John Szakmeister
  • 41,719
  • 9
  • 84
  • 75