Where did the "None"s come from? | Python map() function [duplicate] - python

This question already has answers here:
"pass" same as "return None" in Python?
(6 answers)
Closed 5 months ago.
I wrote a little code that uses the map() function:
def function(a):
if a % 2 == 0:
return a
else:
pass
x = map(function, (1,3,2,5,6))
print(set(x))
It's supposed to return every even number that is provided, If it's an odd number, I don't want it to return anything, so I put "pass". However, when I run it, the output goes like this:
{2, 6, None}
This is weird, I'm not sure where the "None" came from, and when I change the set() function that is used to print the X to either list() or tuple(), the output goes like these:
[None, None, 2, None, 6] or (None, None, 2, None, 6)
I'm not really sure what's going on here, the odd numbers weren't supposed to return anything but instead, it's still there as "None". Is there a way I could fix this? What caused this in the first place?

Every Python function returns something. If no return statement is executed, or the return statement has no expression, then the function returns None. And that's where your Nones come from.
If you want to filter a list of values by some criterion, write a function which returns True or False (or equivalents), and use the filter built-in:
>>> def isEven(a):
... return a % 2 == 0
>>> [*filter(isEven, (1,3,2,5,6))]
[2, 6]
[*generator] turns a generator into a list. That also works with sets, using {*generator}; for tuples, you need a trailing comma: (*generator,). (Thanks, #MustafaAydin.)

Related

Function that accepts an int, a list, or a tuple and returns true if it is a list [duplicate]

This question already has answers here:
Determine the type of an object? [duplicate]
(15 answers)
Closed 7 months ago.
I am trying to make my own function that receives an int, a list, or a tuple. The function returns true if it is a list else a false if it not a list. But I keep getting none or false when I try to run it.
def int_list_tuple(value):
if value==list:
return True
if value !=list:
return False
print(int_list_tuple(6))
print(int_list_tuple([6, 7, 9]))
print(int_list_tuple((6, 2)))
There is already a function for that
isinstance(obj, list)
If you want to do it this way, which isn't recommended at all for good programming practices... (You should really be asking yourself why you need to do this.)
def list_check(value):
if isinstance(value, list):
return True
return False
print(list_check(6))
print(list_check([6, 7, 9]))
print(list_check((6, 2)))
Another not-as-durable way of doing this is like in the linked duplicate question.
print(type(6) is list)
print(type([6, 7, 9]) is list)
print(type ((6, 2)) is list)
The problem is that if you are needing to check for type, while sometimes unavoidable, should be avoided.

Un-usual behaviour of list comprehension in python [duplicate]

This question already has answers here:
Why does the print function return None?
(1 answer)
Understanding Python 3 lists printing None value for each element [duplicate]
(2 answers)
Closed 3 years ago.
I'm trying to understand List-comprehensions in python , I came across this behaviour of list comprehension. when I do:
[print(y) for y in range(0,10)] it gives response
0
1
2
3
4
5
6
7
8
9
[None, None, None, None, None, None, None, None, None, None]
I understand it prints 0 to 9, but I don't understand why it prints None .But when I do o = [print(y) for y in range(0,10)] it prints
0
1
2
3
4
5
6
7
8
9
This time without any none,I couldn't find any relevant stuff by searching, can someone please explain , Thanks
If you type anything from the interpreter, it will echo whatever the function or expression returns, unless it is None (the default).
For example:
>>> 1+1
2
Similarly, the print function calls get executed while the expression is being built, but the list of Nones is actually the result of the expression.
You probably want to do something with it, so either:
[y for y in range(0,10)]
Or:
mylist = [y for y in range(0,10)]
Makes more sense. The print function prints the value, but then returns None and the value it printed is lost.
The print function returns None, and you put these Nones into your list. The elements are what the function returns, not what is printed on the screen. The printing-on-the-screen part is a side-effect of the print function.
Since there are already plenty of other answers showing what you probably wanted to do, I will not reproduce them here.
Because you are basically doing thing like this:
x = []
for y in range(0,10):
x.append(print(y))
print(x)
You should try [y for y in range(10)] instead.
It is because print function prints output to the console, not to the list. This will give you your result:
[y for y in range(0,10)]
Or
list(map(lambda y: y, range(0,10)))

Python - Recursive Function Without Return Logic [duplicate]

This question already has answers here:
Why does my recursive function return None?
(4 answers)
Closed 4 years ago.
I had trouble understanding why this function returns None:
def rem(x, a):
"""
x: a non-negative integer argument
a: a positive integer argument
returns: integer, the remainder when x is divided by a.
"""
if x == a:
return 0
elif x < a:
return x
else:
rem(x-a, a)
rem(7, 5)
I then realized that the last line in the function should be:
return rem(x-a, a)
I am still unsure as to what really happens in the first one. It looks like there are 2 seperate function calls, one returning 2 and the other None... any help?
All python function returns None if it doesn't terminate by a return statement. In your case, you successfully called the recursion but you discarded the result in the else part. And after the if-block, the default return None is implicitly executed.

Python: removing an item from a list in the if statement condition? [duplicate]

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 4 years ago.
I have this code:
myList = [1, 2, 3, 4, 5]
if (myList.remove(4)):
print "We removed 4, so this is true!"
print myList
When I run it, this is what I get:
[1, 2, 3, 5]
So it appears that the "4" was removed from the list as specified in the condition of the if statement, yet the if statement did not end up being "True" since the print statement did not print to the console. Why is it that the if statement is false?
myList.remove(4) does not return True or False depending on whether the remove operation was successful or not.
Instead, it returns nothing (i.e. None) if successful and raises a ValueError otherwise.
Thus,
if mylist.remove(4):
translates to
if None:
which is False
From the docs:
list.remove(x)
Remove the first item from the list whose value is equal to x. It is an error if there is no such item.
So .remove() either returns None or raises a ValueError, hence it equates to False in your code. Here is a link to the relevant docs for further reading.
The remove function doesn't actually return anything. So, the if statement if checking for a value, doesn't get one, which means the if statement results in a false.
myList = [1, 2, 3, 4, 5]
var1 = myList[3]
if var1:
print "1 - Got a true expression value"
print var1
var2 = myList.remove(4) # Nothing returned (var2 = None)
if var2: # if statement fails because var2 is None
print "2 - Got a true expression value"
print var2
print myList
This will result in the following when the code is executed
1 - Got a true expression value
4
[1,2,3,5]
Because .remove, like del, it doesn't return anything. So, it implicitly returns None, which is evaluates to False in a Boolean expression.
The .remove method for lists returns None when the item was found, and throws an error if not.
Here is one option:
a=[1,2,3,4]
try:
a.remove(4)
print "we removed 4, so this is true!"
except:
pass
print(a)

Python - How to get a function to actually return `None`? [duplicate]

This question already has an answer here:
Why do I get extra output from code using 'print' (or output at all, using 'return') at the REPL, but not in a script?
(1 answer)
Closed 26 days ago.
Output for:
def test(c):
if c == 4:
return None
return 'test'
returns 'test' given anything I put in such as test(500) but when I try test(4) the function simply skips and pretends I never ran it, but I want it to show None. So,
>> test(500)
'test'
>> test(4)
>>
is what happens. My goal is for a None to return without having to use print in the function:
>> test(4)
None
Help!
It is returning None. Nothing is printed, because the output shows the result, which is None, which is nothing, so it is not shown.
It is returning None. If you want to see that this is true without putting print in the method definition, you can do this:
print test(4)
> None
None is the result returned by things that "don't return anything", like list.sort or the Python 3 print function. If an expression you type at the interactive prompt evaluates to None, Python won't automatically print it, since it thinks you probably called a "doesn't return anything" function, and it would be confusing to have sessions like
>>> l = [3, 2, 1]
>>> l.sort()
None
>>> print(l)
[1, 2, 3]
None
If you want to print it anyway, you need to explicitly print it.

Categories

Resources