I need to append the elements of one list to a new list based on the values of a third list

Question:

Working in python for a class assignment.

I have a list with each element being a sentence with type string.

I have another list with each element being a 1 or 0 based on each sentence of the first list.

So each element sentence has a score of either 1 or 0. I’m trying to create a third list using a for loop

This is the code I was expecting to work and I can’t seem to find a better solution online.

sentences = ['The house is big','Look at the tree','He is eating food']
scores = [1,0,1]
newlist = []
for i in scores:
    if i == 1:
        newlist.append(sentences[i])
print(newlist)

I want my newlist to include [‘The house is big’, ‘He is eating food’]

How would I achieve this?

Asked By: Brady Monks

||

Answers:

Two solutions come to mind, first you can use zip for a more Pythonic approach to iterate over values in both lists simultaneously:

sentences = ["The house is big", "Look at the tree", "He is eating food"]
scores = [1, 0, 1]
new_list = []

for string, score in zip(sentences, scores):
    if score == 1:
        new_list.append(string)

print(new_list)

You can also shorten it to a list comprehension (in which case you don’t need a for loop like above):

new_list = [string for string, score in zip(sentences, scores) if score == 1]

Another way could be to use enumerate to get the indices you need, because the current issue is that you are trying to access an index that has the same value as the score which is either 1 or 0 so you will always get only the second item from sentences:

sentences = ["The house is big", "Look at the tree", "He is eating food"]
scores = [1, 0, 1]
new_list = []

for index, score in enumerate(scores):
    if score == 1:
        new_list.append(sentences[index])

print(new_list)

Again, you can use a list comprehension too:

new_list = [sentences[index] for index, score in enumerate(scores) if score == 1]
Answered By: Matiiss

You are looping through scores thus you are doing this:

Appending sentence[1] because i = 1 in the first iteration

Then appending nothing because i != 1

Then appending sentence[1] again because i = 1 on the 3rd
iteration

You could use zip to iterate both iterables at once. Here’s an example:

new_list = [sentence for i, sentence in zip(scores, sentences) if i == 1]
Answered By: Jab
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.