0

This is the initial code:

word_list = ['cat','dog','rabbit']
letter_list = [ ]
for a_word in word_list:
   for a_letter in a_word:
      letter_list.append(a_letter)
print(letter_list)

I need to modify it to produce a list of unique letters.

Could somebody please advise how to do this without using set()

The result should be like this

> ['c', 'a', 't', 'd', 'o', 'g', 'r', 'b', 'i']
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213
user1014691
  • 79
  • 1
  • 9

6 Answers6

2

Only problem that I can see is that you have not checked if the letter is already present in list or not. Try this:

>>> word_list= ['cat', 'dog', 'rabbit']
>>> letter_list= []
>>> for a_word in word_list:
    for a_letter in a_word:
        if a_letter not in letter_list:
            letter_list.append(a_letter)


>>> print letter_list
['c', 'a', 't', 'd', 'o', 'g', 'r', 'b', 'i']
Himanshu
  • 1,002
  • 9
  • 22
1

You can do like this:

>>> word_list = ['cat', 'dog', 'rabbit']
>>> chars = [char for word in word_list for char in list(word)] # combine all chars
>>> letter_list = [ii for n, ii in enumerate(chars) if ii not in chars[:n]] # remove duplicated chars
>>>
>>> print letter_list
['c', 'a', 't', 'd', 'o', 'g', 'r', 'b', 'i']

Hope it helps.

Eric
  • 2,636
  • 21
  • 25
1

Just place this condition : if a_letter not in letter_list after the second for loop.

0

Use a dictionary, it is optimized for key based random look-ups. Keep the value as 1 if the key is encountered. Finally, extract all the keys at the end.

unique_chars = {}
word_list = ['cat','dog','rabbit']
for word in word_list:
    for alph in word:
        unique_chars[alph] = 1 #or any other value
letter_list = unique_chars.keys()
gokul_uf
  • 740
  • 1
  • 8
  • 21
0

All you have to do is add a condition :

if a_letter not in letter_list

And add the a_letter is not in the letter_list

The code is as follows :

word_list = ['cat','dog','rabbit']
letter_list = []

for a_word in word_list:
   for a_letter in a_word:
      if a_letter not in letter_list
        letter_list.append(a_letter)

print(letter_list)

The output for this would be :

['c', 'a', 't', 'd', 'o', 'g', 'r', 'b', 'i']
The Room
  • 758
  • 1
  • 9
  • 22
0
li = [char for word in word_list for char in word] # create list with individual characters
li_without_duplicates = list(dict.fromkeys(li)) #remove duplicates
print(li_without_duplicates)


jay fegade
  • 83
  • 8