Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

list comprehension else nothing python

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']

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Someone can help me? ;-

>Solution :

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']
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading