'How to check if words in list have double letters and create a new list with words that do have double letters using python?

This is what I tried:

L=["ss","dd","da","ne","kk"]

L1=[]

for i in L:

    if L[i]==L[i+1]:

        L1.append[i]

print(L1)

But it says, list indices must be integers or slices, not str. What should I do?



Solution 1:[1]

Ideally, use a list comprehension:

L1 = [e for e in L if e[0]==e[1]]

output: ['ss', 'dd', 'kk']

Or modifying your code:

L1=[]

for e in L:
    if e[0] == e[1]:
        L1.append(e)

Solution 2:[2]

You could turn each word into a set and compare the length of that set - which only retains unique characters - to the length of the original word:

words = ["ss","dd","da","ne","kk"]
doubles = [w for w in words if len(set(w)) < len(w)]

print(doubles)

which should give you:

['ss', 'dd', 'kk']

Solution 3:[3]

The reason your code does not work is because i represents every element in the list, L. Instead, you are treating i as an index. If it were an index, we would instead use: for i in range(len(L)):

Additionally, when using the .append() function, or any function for that matter, we pass in our argument using parentheses, not brackets.

To solve the problem, we can modify our if statement so that if the first character of i equals the second character of i, then we append i to L1:

L=["ss","dd","da","ne","kk"]

L1=[]

for i in L:

    if i[0] == i[1]:

        L1.append(i)

print(L1)

Output:

['ss', 'dd', 'kk']

This works for all lists where every element has only 2 characters. If we want this to work for all lengths of Strings, we can create a function that checks if a word has double letters:

def hasDoubleLetters(i):
  for x in range(len(i) - 1):
    if i[x] == i[x + 1]:
      return True
  return False

This function will iterate through the all characters but the last one, and check if it is equal to the following character. If so, the function returns True. If the function finishes iterating and has not returned True, the function returns False.

def hasDoubleLetters(i):
  for x in range(len(i) - 1):
    if i[x] == i[x + 1]:
      return True
  return False

L=["ss","dd","da","book", "house"]

L1=[]

for i in L:
  if hasDoubleLetters(i):
    L1.append(i)

print(L1)

Output:

['ss', 'dd', 'book']

I hope this helped answer your question! Please let me know if you need any further clarification or details :)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 mozway
Solution 2 oriberu
Solution 3