-1

Say I have list of 5 words

my_list = ['python', 'apple', 'always', 'sky', 'lie']

How can I use a function to scan each word individually and delete any word that has the same letter occur more than once?

So after the function runs, the list should only contain

my_list = ['python', 'sky', 'lie']
Yu Hao
  • 119,891
  • 44
  • 235
  • 294
MLJezus
  • 79
  • 1
  • 9

3 Answers3

2

A one-liner:

result = [item for item in my_list if len(item) == len(set(item))]
  • Use list comprehension to make a new list
  • Use set to check if the length changes(which means there is duplicate)

You can write a function to make it more readable:

def is_unique_string(s):
    return len(s) == len(set(s))

result = [item for item in my_list if is_unique_string(s)]

There is already a discussion here: Counting repeated characters in a string in Python.

cizixs
  • 12,931
  • 6
  • 48
  • 60
0

Here is your answer

list = ['python', 'apple', 'always', 'sky', 'lie']
new_list = []
for string in list:
    if len(string) == len(set(string)):
        new_list.append(string)

print(new_list)
Gahan
  • 4,075
  • 4
  • 24
  • 44
0
def has_duplicate(s):
    for x in xrange(len(s)-1):
       if s[x] in s[x+1:]:
         return true
    return false

l=["python", "apple", "always", "sky", "lie"]
y=[s for s in l if not has_duplicate(s)]

Check if the n_th character is in the string sliced at the n_th character. ie

"apple"

  • checks "a" in "pple"
  • checks "p" in "ple", match
xvan
  • 4,554
  • 1
  • 22
  • 37