Iterate over a list, to check if character is present, using a for loop. If present, put character into a new list at that same spot

Viewed 4467

I'm trying to accomplish 2 things here. First, I need to check a list, to see if a particular character is present on the list.

If the character is in the list, then I'd want to put that character into a separate list at the same exact spot in the index, and if it's not present, the list would just have a null in whatever spots don't have that letter. So hypothetically in the example below, if I'm checking for the letter L, I'd want to return a list that reads word2 = ['','','L','L',''].

I've been trying this with a for loop, but I can't seem to return what I'm looking for. Any help is greatly appreciated, thanks very much!

letter = 'L'  
word = ['H','E','L','L','O']  
word2 = []  

for i in word:  
     if letter in word:  
5 Answers

you can use a list comprehension:

letter = 'L'
word = ['H','E','L','L','O']
word2 = [w if w == letter else '' for w in word]
word2

output:

['', '', 'L', 'L', '']

or you can use a simple for loop:

word2 = []
for w in word:  
    if w  == letter:
        word2.append(letter)
    else:
        word2.append('')

What you want is to check char equality, you may iterate over the chars of the word, and it equal to the specific letter : keep it, else put a empty char

for word_letter in word:
    if word_letter == letter:
        word2.append(word_letter)
    else:
        word2.append("")

Inline the if inside the append

for word_letter in word:
    word2.append(word_letter if word_letter == letter else "")

Inline the for into a list comprehension

word2 = [word_letter if word_letter == letter else "" for word_letter in word]

Guess the word game

If you want the user to guess the word, you may need to check against multiple letters, and not once, for that store the letters in a list, and instead of checking equality, check for inclusion in the list of tries

tries = []
word = ['H', 'E', 'L', 'L', 'O']
word2 = [word_letter if word_letter in tries else "" for word_letter in word]

while "" in word2:  # a letter is still empty
    letter = input("Try a letter :")
    tries.append(letter)
    word2 = [word_letter if word_letter in tries else "" for word_letter in word]
    print("Word is now", word2)
letter = 'L'  
word = ['H','E','L','L','O']  

indices = [i for i, w in enumerate(word) if w == letter]
new_word = [''] * len(word)
for i in indices:
  new_word[i] = letter
print(new_word)

Another simple solution using lambda:

letter = 'L'  
word = ['H','E','L','L','O']
new_word = map(lambda w: letter if w == letter else '', word)
print(new_word)

Just a reminder that in Python strings are iterable and if you don't really need a list of characters you could do:

letter = 'L'
word = 'HELLO'

word2 = ''.join(c if c == letter else ' ' for c in word)

When using Python, you should avoid thinking in terms of index. Approach the problem from the perspective of applying a transformation to elements of a list to obtain another. This is what list comprehensions are for.

def keepL(letter): return letter if letter == "L" else ""

word2 = [ keepL(letter) for letter in word ]

There are a slew of other tricks you can use to process strings such as multiplication by a number to repeat a string (including zero times) and treating bookeans (comparison results) as 0 or 1.

Combining these, your list comprehension can do the job without defining a function (in this particular case):

word2 = [ letter*(letter=="L") for letter in word ]

multiplies the letter by 1 or zero depending on whether it's an 'L' or not.

Related