Ad

Want Create A New List From Existing List Using If Else Statement

I want to create a new list using existing list "dta", where i do not want a value for "banana" but a numeric for others. desired list is below:

[1,3,4,5,6]

but when i am trying to print of my final list "d" then i get only single value.

dta=list(["apple","banana","pine","cucumber","Guava","Coconut"])

d=[]
def cont_list(x):

for i in x:
    if i=="banana":
        continue
if i=="pine":
    d.append(3)

elif i=="apple":
    d.append(1)

elif i=="cucumber":
    d.append(4)
elif i=="Guava":
    d.append(5)
else:
    d.append(6)

return d   

cont_list(dta)
print(d)
Ad

Answer

you can do it with list comprehension:

dta = ["apple","banana","pine","cucumber","Guava","Coconut"]

d = [idx for idx in range(1,len(dta)+1) if dta[idx-1] != "banana"]
print (d)

in function:

dta=list(["apple","banana","pine","cucumber","Guava","Coconut"])

def cont_list(x):
    dta = ["apple","banana","pine","cucumber","Guava","Coconut"]
    d = [idx for idx in range(1,len(dta)+1) if dta[idx-1] != "banana"]
    return d
print (cont_list(dta))

output:

[1, 3, 4, 5, 6]

NOTE: your code will be ok if you fix INDENTION:

d=[]
def cont_list(x):

    for i in x:
        if i=="banana":
            continue
        if i =="pine":
            d.append(3)

        elif i=="apple":
            d.append(1)

        elif i=="cucumber":
            d.append(4)
        elif i=="Guava":
            d.append(5)
        else:
            d.append(6)
    return d

cont_list(dta)
print(d)

or you can do it like:

d=[]
def cont_list(x):

    for i in range(len(x)):
        if x[i]=="banana":
            continue
        else:
            d.append(i+1)
    return d

cont_list(dta)
print(d)
Ad
source: stackoverflow.com
Ad