Milan Pjevic
Milan Pjevic

Reputation: 17

How to make third list from two lists of strings and one condition?

I have two lists of strings. The first list is containing all English words. The second one contains capital letters (A-Z). What I need is to create the third list that will not have any containing capital letters.

example:

words = ["Apple", "apple", "Juice", "tomato", "orange", "Blackberry"]

let = ["A", "B"]

The result of third list should be:

new_lst = ["apple", "Juice", "tomato", "orange"]

What I tried is just not correct. I tried something like this.

new_lst = [ ]

for word in words:
    for l in let:
        if l not in word:
            new_lst.append(word)

print(new_lst)

I am aware of incorrect code, but apparently my brain did not find any solution for more than one hour, so if someone has mercy on me... Please, help me see it.

Thank you.

Upvotes: 0

Views: 105

Answers (2)

Daweo
Daweo

Reputation: 36450

You might use set's method to deal with that task, following way:

words = ["Apple", "apple", "Juice", "tomato", "orange", "Blackberry"]
let = set(["A", "B"])  # equivalent to: let = set("AB")
new_lst = [i for i in words if let.isdisjoint(i)]
print(new_lst)  # ['apple', 'Juice', 'tomato', 'orange']

Note that I used let which is set, thus has method isdisjoint, which accepts iterable, so there is no need for implicit conversion of argument to set.

Upvotes: 0

Tomerikoo
Tomerikoo

Reputation: 19414

Indeed your condition will fail for the word Apple and letter A, but then when l = 'B' the word will be added anyway (because 'B' not in "Apple").

You can use all here to make sure all letters from let are not in word:

for word in words:
    if all(l not in word for l in let):
        new_lst.append(word)

Or simply:

for word in words:
    if word[0] not in let:
        new_lst.append(word)

which can be written as list-comprehension:

new_lst = [word for word in words if word[0] not in let]

Alternatively, you can reverse your logic to remove elements instead of add them:

new_lst = words[:]  # create a copy of words

for word in words:
    for l in let:
        if l in word:
            new_lst.remove(word)
            break  # no need to check rest of the letters
print(new_lst)

Or:

new_lst = words[:]  # create a copy of words

for word in words:
    if word[0] in let:
        new_lst.remove(word)
print(new_lst)

Upvotes: 1

Related Questions