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

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)))

Related

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

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.)

How Generator expressions work internally in python? [duplicate]

This question already has answers here:
What does the "yield" keyword do in Python?
(51 answers)
Why does the print function return None?
(1 answer)
Closed 2 years ago.
I have tried this following code:
result = (x for x in range(3))
for y in result:
print(y)
I am getting the following Output:
0
1
2
But when I am using this code :
result = (print(x) for x in range(3))
for y in result:
print(y)
I am getting the following output:
0
None
1
None
2
None
Can anyone explain, Why this None is coming in output in second code?
Because print(x) prints the value of x (which is the digits that get printed) and also returns None (which is the Nones that get printed)
print doesn't return a value, so you are seeing None, which is the return for print, and the output from print. This is a classic case of using comprehension syntax for side effects, which is not using the generator/comprehension syntax to contain an actual result. You can check this by running:
print(print('x'))
x
None

if x or y in LIST is always true even if it is not [duplicate]

This question already has answers here:
How to test the membership of multiple values in a list
(12 answers)
Closed 3 years ago.
I have an if statement which always returns as true even if it is not.
I have a global list :
NUMBERS_LIST = []
Numbers get added to it via an API call, that works fine.
When it does the following:
def func():
if 8 or 9 in NUMBER_LIST:
return true
elif 1 or 2 in NUMBER_LIST:
return true
But for some reason, it always returns true on the first if statement, even if NUMBER_LIST = [1]
I debugged my program and can see that NUMBER_LIST does contain 1, it's type is int.
I tried doing int(8), converting both types to str but that did not fix my issue.
When I debugged and step through the program, it doesn't really tell me much, I am using Pycharm.
or does not distribute. What you have written is not equivalent to
if 8 in NUMBER_LIST or 9 in NUMBER_LIST:
which is what you want, but to
if 8 or (9 in NUMBER_LIST):
Since 8 is a truthy value, the containment operation is never evaluated.

List comprehension syntax - how to use ... if... else? [duplicate]

This question already has answers here:
if/else in a list comprehension
(12 answers)
Is it possible to use 'else' in a list comprehension? [duplicate]
(6 answers)
Closed 3 years ago.
I'm just getting started with Python and was reading about list comprehensions.
The following code:
my_list = [x ** x for x in range(1,11) if x % 2 == 0]
print(my_list)
... produces this output:
[4, 256, 46656, 16777216, 10000000000]
I then tried this code:
my_list = [x ** x for x in range(1,11) if x % 2 == 0 else 7]
print(my_list)
... but I got a syntax error starting at the second "e" in else.
Can someone explain why I'm getting a syntax error? I'd like to have the list create a list of even squares based on the value of the base (x), and to have the value "49" if the list value is not an "even number" square.
In this case, you would want
my_list = [x ** x if x % 2 == 0 else 49 for x in range(1,11)]
If you use an if at the end of a list comprehension like that, it is used to select which elements to include. If you want a different result depending on the case, you need to use a ternary if at the beginning instead.
For more info, take a look at the docs here. To quote:
A list comprehension consists of brackets containing an expression followed by a for clause, then zero or more for or if clauses. The result will be a new list resulting from evaluating the expression in the context of the for and if clauses which follow it.
There is no support for else here, presumably because a ternary if (if condition then foo else bar) in the 'body' of the comprehension already accomplishes this and "There should be one-- and preferably only one --obvious way to do it."

Need help to understand code in python [duplicate]

This question already has answers here:
How to test multiple variables for equality against a single value?
(31 answers)
Closed 8 years ago.
first = int(input('first int: '))
second = int (input('second int: '))
result =0
if first and second:
result =1
elif not first:
result =2
elif first or second:
result=3
else:
result=4
print(result)
when I enter 1 and 0, the result is 3. I would appreciate if anyone could add some explanation.
You are using or- it means the statement will return True when it first finds True.
When you say 5 or 9, both 5 and 9 represent truism (as does any non-zero value). So it returns the first - 5 in this case. When you say 9 or 5, it returns 9.
EDIT: k = 1 or 0 would evaluate to True since 1 represents truism. Thus, as per your code, result is 3
In many program languages, the boolean operations only evaluate their second argument if needed for their outcome. These called short-circuit operator. And in python, according the docs, it returns:
x or y : if x is false, then y, else x
x and y : if x is false, then x, else y

Categories

Resources