0

I come from a C/C++ background and I can't find out how this works in python.

In C++, return values are stored in a temporary variable and can be used/reassigned. So I can do something like this:

   int foo() {
       return 1; 
    }

    int main() {
       int x = foo() + 1;
       return 0; 
    }

I thought this works the same in Python and until now, it did. But how come this won't work when using list comprehension:

print([i for i in range(5)].append(5)) 

I expected a list from 0-5, but I get None.

To work around this problem, I need to first assign my list to a variable:

my_list = [i for i in range(5)]
my_list.append(1)
print(my_list)

So list comprehensions creates new list from some iterator but doesn't return the new list? But somehow if I assign it to a variable it does return the new list? Confused

Thanks for reading.

GHe
  • 499
  • 1
  • 4
  • 10
  • 2
    This isn't specific to list comprehensions. `print([1,2,3].append(4))` will display `None` too. – Kevin Jun 09 '16 at 19:18
  • 3
    There are probably more canonical dupes -- But here is one: http://stackoverflow.com/q/16641119/748858 – mgilson Jun 09 '16 at 19:19
  • 3
    `append()` is a function that `list` type implements. It does not return anything, instead it modifies the list instance on which `append()` was invoked. – Brian Cain Jun 09 '16 at 19:19
  • 2
    Would you have been surprised by an error from `std::cout << get_vector().push_back(thing);`? – user2357112 Jun 09 '16 at 19:21
  • When you don't understand the behaviour, check your assumptions. Look closely at the code: `print([i for i in range(5)].append(5))`. Given that `None` is displayed, *what is the expression* that must be evaluating to `None`? The argument to `print`, right? Which is the entire thing, `[i for i in range(5)].append(5)`, right? Now, notice that it **didn't cause an exception** looking up the `append` method. Can `.append` be called on `None`? No? It's called on a list, right? So `[i for i in range(5)]` *is* returning a list. By process of elimination, what is returning `None`? – Karl Knechtel Sep 15 '22 at 00:47

0 Answers0