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 3 years ago.
My following code is supposed to collect numeric inputs from the user, put it in a list, and sort them:
def build_list():
"""Builds a list by continually collecting input from the user until 'done' is provided."""
raw_list = []
while True:
item = input("Enter a numeric value: ")
if item.lower() == "done":
break
try:
item = int(item)
except ValueError:
print("That wasn't a valid number. Try again or enter 'done' to stop making the list.")
else:
raw_list.append(item)
return raw_list
def sort_list(unsorted_list):
sorted_list = unsorted_list.sort()
return sorted_list
def main():
my_list = build_list()
my_list = sort_list(my_list)
print(my_list)
if __name__ == '__main__':
main()
This piece of code is printing "None" instead of printing my sorted list. What step am I missing here?
The sort() fonction (as well as the reverse() function) works "in-place" and always return None.
You should write:
def sort_list(unsorted_list):
sorted_list = list(unsorted_list) # local copy if needed
sorted_list.sort()
return sorted_list
You can also use the sorted() function:
def sort_list(unsorted_list):
sorted_list = sorted(unsorted_list)
return sorted_list
See: Sorting HOW TO
sort sorts a list inplace and returns None. Either call sort without returning it:
def main():
my_list = build_list()
my_list.sort() # Here
print(my_list)
or use sorted:
def main():
my_list = build_list()
my_list = sorted(my_list) # Here
print(my_list)
Related
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]))
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.
I'm learning Python and trying to solve the same problem ("Friend or Foe?"). I wrote the code below and would like to find out how to move-on following "my logic" way.
It seems that it adds just the very first item to the new_friends list but doesn't iterate over all the elements of x list.
Beside above, the return value is None ... what am I not noticing here?
def friend(x):
x = ["Ryan", "Kieran", "Jason", "Yous"]
new_friends = []
for str in x:
if len(str) == 4:
return new_friends.append(str)
return new_friends[0:]
Instead of if statement I also tried a nested while loop .. but no success adding other items to the new_friends list.
Here's a fixed up version of your function that does what I believe you want:
def friend(x):
new_friends = []
for str in x:
if len(str) == 4:
new_friends.append(str) # no 'return' here
return new_friends # return resulting list. no need to return a slice of it
Here's a more concise version that uses a list comprehension:
def friend(candidates):
return [candidate for candidate in candidates if len(candidate) == 4]
For either version of the function, this:
print(friend(["Ryan", "Kieran", "Jason", "Yous"]))
results in this:
['Ryan', 'Yous']
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:
Python list comprehension: test function return
(2 answers)
Closed 6 years ago.
I have a function which has a for loop like this
def my_func():
order = [1,2,3,4,5,6,7]
my_list = []
for o in order:
tmp = is_odd(o)
if tmp:
my_list.append(tmp)
return my_list
def is_odd(n):
if n%2 != 0:
return n
else:
return False
I want to convert it into one line python for loop. I did it like this
def my_func():
order = [1,2,3,4,5,6,7]
my_list = [is_odd(o) for o in order if is_odd(o)]
return my_list
def is_odd(n):
if n%2 != 0:
return n
else:
return False
The problem with this code is that it call is_odd function twice in each loop iteration. Is there any other way to convert loop into one line loop and calling is_odd function only once?
(This is not original code. Just an example)
As described in the question's answers that I've linked as duplicate to your question:
Python list comprehension: test function return
You'd create a generator (or a list) that produces the (intermediate) results of your function's calls and produce the filtered output based on that:
Example:
def my_func():
order = [1,2,3,4,5,6,7]
intermediate_results = (is_odd(o) for o in order)
# alternatively filter using `filter(None, intermediate_results)`
return [i for i in intermediate_results if i]
In this case, you can use the filter function. E.g. my_list = filter(is_odd, order).
If you have similar needs, look at the itertools module.
Hi – it looks like you return the function is_odd(o) (thus run it again) for the instances of o where the function is_odd(o) returns true. Following should only run once:
def my_func():
order = [1,2,3,4,5,6,7]
my_list = [o for o in order if is_odd(o)]
return my_list