简体   繁体   中英

Why does my list stay empty despite adding elements using a for loop

I'm trying to do the following: - check if the element from one list exists in another list. If so, do nothing, if not append it to that list.

Simplefied example code:

x=[1,2,3]
y=[2,3,4]

for item in x:
    if item in y=='False':
        y.append(item)
    else:
        continue
print(y)

Unfortunately it does not work and as a beginner I'm not sure why. Any thoughts?

The reason why your code doesn't work, is that the statement:

if item in y=='False':

checks if the boolean answer of the condition

item in y

is equal to the string 'False' for it to trigger the if block.


Based on your question, the code correction should be:

if item not in y:
    y.append(item)

In the above example, the if block is entered when there is an item in x that is not present in list y

x=[1,2,3]
y=[2,3,4]

for item in x:
    if item not in y:
        y.append(item)
    else:
        continue
print(y)

Gives:

[2, 3, 4, 1]

You should use:

x=[1,2,3]
y=[2,3,4]

for item in x:
    if item not in y:
        y.append(item)
    else:
        continue
print(y)

The line: if item in y=='False': will never be true because if an item is not in y, it will return the boolean False, not the string 'False'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM