This question already has answers here:
Why do these list operations (methods: clear / extend / reverse / append / sort / remove) return None, rather than the resulting list?
(6 answers)
Closed 1 year ago.
I have been studying coding on my own and some how I have been stuck, not being able to compile the same solution:
my code:
def append_size(lst):
num = len(lst)
lst = lst.append(num)
return lst
print(append_size([23, 42, 108]))
solution:
def append_size(lst):
lst.append(len(lst))
return lst
print(append_size([23, 42, 108]))
first one gives out "None" and second one gives out the list.
tell me why.
Thank you🤘
Its because in the first one, you assign lst the result of the call lst.append()
The .append() method returns None so assigning it to a variable and returning it... Would return None
While in the second case. No such assignment takes place
# first code
lst = lst.append(x) # end up assigning None to lst
#second code
lst.append(x) # no unwanted assignments
.append() wont return anything (just None), it just modifies a list. So when you do lst = lst.append(list) you are basically assigning None to lst.
Try this instead
def append_size(lst):
num = len(lst)
lst.append(num)
return lst
print(append_size([23, 42, 108]))
Related
This question already has answers here:
Python append replaces the existing list with None
(2 answers)
Closed 1 year ago.
In the code below, it says it cannot append "a" because it is class NoneType but just before that line, it is able to print the list and print its type. Why does it lose its type on the next line?
from itertools import combinations_with_replacement
def output_list_of_feature_names(degree, list_of_feature_names):
a = ["as", "asd"]
for i in range(1, degree + 1):
for item in combinations_with_replacement(list_of_feature_names, r = i):
print(a)
print(type(a))
print(a)
a = a.append(item)
return a
output_list_of_feature_names(2, ["throttle", "angle", "final_vert_speed"])
a = a.append(item)
is the offending line. a.append is a function that modifies the list in-place and returns None. That return value is then assigned to a.
To fix, change to:
a.append(item)
This question already has answers here:
Why do these list operations (methods: clear / extend / reverse / append / sort / remove) return None, rather than the resulting list?
(6 answers)
Closed 2 years ago.
How can I create a Python custom function to get list of strings having length more than a number n when we pass number n and list of strings?
I tried using this function but it returns None:
lst=['shiva', 'patel', 'ram','krishna', 'bran']
filtered_list=[]
def word_remove(n, lst):
for i in lst:
if len(i)>n:
return filtered_list.append(i)
print(word_remove(4,lst))
The output is :
None
append method on a list does not return any value. Hence the None type.
Append function has no return type. Try instead this.
def word_remove(n, lst):
for i in lst:
if len(i) > n:
filtered_list.append(i)
return filtered_list
lst = ['shiva', 'patel', 'ram','krishna', 'bran']
filtered_list=[]
def word_remove(n, lst):
for i in lst:
if len(i)>n:
filtered_list.append(i)
return filtered_list
print (word_remove(4,lst))
Output:
['shiva', 'patel', 'krishna']
The method append does not return anything. So you need to return the whole filtered_list.
This question already has answers here:
How can I use `return` to get back multiple values from a loop? Can I put them in a list?
(2 answers)
Closed last month.
I was trying to use *args with a for loop in python, however I don't see how to return all the values passed to the function, which should return all the even numbers
def f_even(*args):
for item in args:
if item%2 == 0:
return item
The above code returns only the first value, as I guess after the return it goes out of the function. Indeed, if I use print instead, it works
I'm trying to find a way to return a tuple with all the even numbers when I pass let's say (1,2,3,4,5) to the function
Thank you!
In python you can use list comprehension to do this. will make you code more readable and will shrink it too.
def f_even(*args):
return [elem for elem in args if elem % 2 == 0]
You could slightly modify you function and make it a generator by using yield. This way your function wont end after returning first even number but will keep yielding them one by one.
def f_even(*args):
for item in args:
if item%2 == 0:
yield item
for i in f_even(1,2,3,4,5):
print(i)
Output:
2
4
Or if you want to store all yielded values:
even_numbers = list(f_even(1,2,3,4,5))
print(even_numbers) # -> [2, 4]
Done, thank you all!!
def f_even(*args):
mylist = []
for item in args:
if item%2 == 0:
mylist.append(item)
return mylist
This question already has answers here:
How can I get a reversed copy of a list (avoid a separate statement when chaining a method after .reverse)?
(11 answers)
Closed 6 years ago.
I can't figure out why my if-else statement doesn't run as expected. I've tried to create code to test for a palindromic string. My print functions show me that the reverse method works, but when I get to the comparison stage I can't get it to return True.
Here is the code:
def is_palindrome(a):
myList = []
for i in a:
myList.append(i)
print myList
new = myList.reverse()
print myList
print new
if myList == new:
return True
else:
return False
print is_palindrome("radar")
This returns False. I have also tried changing the if statement to if myList is new: but unfortunately it still returns False.
Any insight appreciated!
list.reverse() is in-place, meaning it reverses the list it is called upon but doesn't return anything.
The line print new should print None, and therefore myList == new will be False.
Instead, use [::-1] which is not in-place and returns a new, reversed list, or use an easier way to detect a palindrome, for example:
def is_palindrome(iterable):
return iterable == iterable[::-1]
This question already has answers here:
Why do these list operations (methods: clear / extend / reverse / append / sort / remove) return None, rather than the resulting list?
(6 answers)
Closed 2 years ago.
I am trying to calculate a postfix expression using Python, but it did not work. I think this is maybe a Python-related problem.
Any suggestions?
expression = [12, 23, 3, '*', '+', 4, '-', 86, 2, '/', '+']
def add(a,b):
return a + b
def multi(a,b):
return a* b
def sub(a,b):
return a - b
def div(a,b):
return a/ b
def calc(opt,x,y):
calculation = {'+':lambda:add(x,y),
'*':lambda:multi(x,y),
'-':lambda:sub(x,y),
'/':lambda:div(x,y)}
return calculation[opt]()
def eval_postfix(expression):
a_list = []
for one in expression:
if type(one)==int:
a_list.append(one)
else:
y=a_list.pop()
x= a_list.pop()
r = calc(one,x,y)
a_list = a_list.append(r)
return content
print eval_postfix(expression)
Just replace a_list = a_list.append(r) with a_list.append(r).
Most functions, methods that change the items of sequence/mapping does return None: list.sort, list.append, dict.clear ...
Not directly related, but see Why doesn’t list.sort() return the sorted list?.
The method append does not return anything:
>>> l=[]
>>> print l.append(2)
None
You must not write:
l = l.append(2)
But simply:
l.append(2)
In your example, replace:
a_list = a_list.append(r)
to
a_list.append(r)
For return data on append use:
b = []
a = b.__add__(['your_data_here'])
append function mutates the list and it returns None. This is the piece of code which does that http://hg.python.org/cpython/file/aa3a7d5e0478/Objects/listobject.c#l791
listappend(PyListObject *self, PyObject *v)
{
if (app1(self, v) == 0)
Py_RETURN_NONE;
return NULL;
}
So, when you say
a_list = a_list.append(r)
you are actually assigning a_list with None. So, the next time when you refer to a_list, it is not pointing to the list but the None. So, as others have suggested, change
a_list = a_list.append(r)
to
a_list.append(r)
Functions like list.append(),list.sort() don't return anything.
e.g
def list_append(p):
p+=[4]
function list_append doesn't have an return statement.so when you run following statements:
a=[1,2,3]
a=list_append(a)
print a
>>>None
but when you run following statements:
a=[1,2,3]
list_append(a)
print a
>>>[1,2,3,4]
That's it.so,hoping it can help you.
List methods can be divided in two types those who mutate the lists in place and return None (literally) and those who leave lists intact and return some value related to the list.
First category:
append
extend
insert
remove
sort
reverse
Second category:
count
index
The following example explains the differences.
lstb=list('Albert')
lstc=list('Einstein')
lstd=lstb+lstc
lstb.extend(lstc)
# Now lstd and lstb are same
print(lstd)
print(lstb)
lstd.insert(6,'|')
# These list-methods modify the lists in place. But the returned
# value is None if successful except for methods like count, pop.
print(lstd)
lstd.remove('|')
print(lstd)
# The following return the None value
lstf=lstd.insert(6,'|')
# Here lstf is not a list.
# Such assignment is incorrect in practice.
# Instead use lstd itself which is what you want.
print(lstf)
lstb.reverse()
print(lstb)
lstb.sort()
print(lstb)
c=lstb.count('n')
print(c)
i=lstb.index('r')
print(i)
pop method does both. It mutates the list as well as return a value.
popped_up=lstc.pop()
print(popped_up)
print(lstc)
just a thought, instead of those functions (which manipulates the actual data) returning None, they should have returned nothing.
Then atleast the user would have caught the issue as it would have throwed an error stating some assignment error!!
Comment your thoughts!!
Just in case somebody ends here, I encountered this behavior while trying to append on a return call
This works as expected
def fun():
li = list(np.random.randint(0,101,4))
li.append("string")
return li
This returns None
def fun():
li = list(np.random.randint(0,101,4))
return li.append("string")