Home > other >  Python - None is returned with .append in if...else
Python - None is returned with .append in if...else

Time:03-17

I need a code which compares values inside a list and returns 1 or 0 in a separate list. My current version returns only None for some reasons. What am I doing wrong?

a=[1,2,3,4,5,9,1,1,2,3,4,5]
d=[]
for i in range(1,len(a)):
    if a[i]>a[i-1]:
        b=1
    else:
        b=0
    f=d.append(b)
print(f)

CodePudding user response:

The reason it returns None is because append() method doesn't have a return value meaning it just updates the original value.
So, your code needs to be like this

a=[1,2,3,4,5,9,1,1,2,3,4,5] 
d=[] 
for i in range(1,len(a)): 
    if a[i]>a[i-1]: 
        b=1 
    else: 
        b=0 
    d.append(b) 
print(d)

CodePudding user response:

some corrections and the script works properly

a=[1,2,3,4,5,9,1,1,2,3,4,5]
d=[]

for i in range(1,len(a)):
    if a[i]>a[i-1]:
        b=1
    else:
        b=0
    d.append(b)
print(d)

CodePudding user response:

I simplify your code as follow:

d = []
f = d.append(1)
print(d)
print(f)

Maybe you can rewrite it as follow:

a=[1,2,3,4,5,9,1,1,2,3,4,5]
d=[]
for i in range(1,len(a)):
    if a[i]>a[i-1]:
        b=1
    else:
        b=0
    d.append(b) 
print(d)
  • Related