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.
Related
This question already has answers here:
Is there a built in function for string natural sort?
(23 answers)
Closed 1 year ago.
a = [
'suit1.png',
'suit10.png',
'suit2.png',
'suit12.png',
'suit3.png',
'suit4.png',
'suit5.png',
'suit6.png',
'suit7.png',
'suit8.png',
]
sorted(a), sorts items in same way as seen in a list
a.sort() also sort list in that way. Is it possible that 'suit10.png' and 'suit12.png' go on the end of list?
Use custom sort as follows:
from functools import cmp_to_key
def cmp_items(a, b):
if int(a.split('suit')[1].split('.png')[0]) > int(b.split('suit')[1].split('.png')[0]):
return 1
elif int(a.split('suit')[1].split('.png')[0]) == int(b.split('suit')[1].split('.png')[0]):
return 0
else:
return -1
cmp_key = cmp_to_key(cmp_items)
a = [
'suit1.png',
'suit10.png',
'suit2.png',
'suit12.png',
'suit3.png',
'suit4.png',
'suit5.png',
'suit6.png',
'suit7.png',
'suit8.png',
]
a.sort(key = cmp_key)
print(a)
Both the sorted function and the list.sort method take an optional key argument which dictates how items are to be sorted. Its value is to be a function that takes a member of the list as an argument and returns a value (usually a number). If a and b are elements of the list, then a will be placed before b if func(a) < func(b).
So, in this case, you could do
a.sort(key=lambda x : int(x[4:].split('.')[0]))
This question already has answers here:
Why do these list methods (append, sort, extend, remove, clear, reverse) return None rather than the resulting list?
(6 answers)
Closed 1 year ago.
Help me understand why this decorator does not add a value to the end of the list that is formed in the do_list () function.
I get the result of the function working with the decorator None
def dec_do_list(func):
def wrapper(arg: int):
result = func(arg).append(4)
return result
return wrapper
#dec_do_list
def do_list(arg: int):
import random
result = []
for i in range(arg):
result.append(random.random())
return result
print(do_list(4))
Thank you in advance!
P.S.
I do this for educational purposes, in order to better understand the Decorator pattern
result = func(arg).append(4)
append doesn't return a new list. It modifies the list in-place. You are getting the result as the return value of append and then returning it so at the end the returned value is None.
You can change it to:
result = func(arg)
result.append(4)
return result
or, in one line:
return func(arg) + [4]
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:
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:
Why do these list operations (methods: clear / extend / reverse / append / sort / remove) return None, rather than the resulting list?
(6 answers)
Closed 8 years ago.
Take these two sample code statments:
result = []
return result.append(feed.entries[0])
&
result = []
result.append(feed.entries[0])
return result
The first gives me an error because the method that result is passed to complains of a NonType not being iterable. Why is this? To me both statements are equivalent
The append method of a list does not return anything
>>> a = []
>>> type(a.append(12))
<type 'NoneType'>
So when you're doing:
return result.append(feed.entries[0])
You're actually returning None in all cases, whereas when you do:
result.append(....)
return result
you're returning the list after it has been mutated (modified) hence giving a the expected result.