I trying to use list comprehension to add names that not in list, and i don't know how to use something like else pass
list_test = []
names = ['Gabriel', 'Lucas', 'Pedro', 'Gabriel', 'Fernando'] # To see the 'Ellipsis' just increase this list
# I know that if i use loop 'for ...' this problem could be solved
# but the original code work like this and i can't change it (this part is only a small slice)
count = 0
while True:
if count == len(names): # breaks when all names are read
break
name = names[count] # Just select each name
list_test.append(name if name not in list_test else) # i don't know what put in else to pass
count = 1
print(list_test)
I Tried else ...
but in original code add 'Ellipsis'
to list, in this code sometimes works, but i need a better solution
I want the output is like:
['Gabriel', 'Lucas', 'Pedro', 'Fernando']
Someone can help me? ;-
CodePudding user response:
If you want to keep unique values in order you can transform to dictionary keys and back to list:
names = ['Gabriel', 'Lucas', 'Pedro', 'Gabriel', 'Fernando']
list_test = list(dict.fromkeys(names).keys())
output:
['Gabriel', 'Lucas', 'Pedro', 'Fernando']
If order does not matter, use a set:
list_test = list(set(names))
(potential) output:
['Lucas', 'Gabriel', 'Pedro', 'Fernando']