-4

Why do the two scenarios below behave differently?

First:

x = []
[x.append('f8') for num in range(8)]
print(x)

Result:

['f8', 'f8', 'f8', 'f8', 'f8', 'f8', 'f8', 'f8']

Second:

x = []
print(list(x.append('f8') for num in range(8))) 

Result:

[None, None, None, None, None, None, None, None]

Why is None passed in the second case? How does list comprehension behave here?

Joyal Mathew
  • 614
  • 7
  • 24
Jeet Singh
  • 303
  • 1
  • 2
  • 10
  • the return value of the `.append` method is `None`. it doesn't return anything, it just modifies the list in place. – Rick Jun 06 '19 at 20:23
  • by the way: the list comprehension is not the correct tool for "do this task some number of times". for that, you should use a regular for loop: `for num in range(8): x.append('f8')`. the list comprehension is for "fill a new list with these values". `.append` is a task, or action, you are doing *to* the list. it does not return anything. – Rick Jun 06 '19 at 20:27
  • 1
    Well, in this particular case the list comprehension *is* the correct tool for "make a list consisting of these items", and if you use one you shouldn't mix it with `append`: `x = ['f8' for _ in range(8)]` – mkrieger1 Jun 06 '19 at 20:29
  • @mkrieger1 yeah, you're right, didn't think of that. – Rick Jun 06 '19 at 20:30
  • i was learning something over internet and was using zip function where i tried putting this directly but got none in combination of other values. So i shortened the problem and got to this code. Thanks very much for clearing the confusion. – Jeet Singh Jun 06 '19 at 20:35

2 Answers2

0

The return value of the list .append() operation is None. Therefore the list

[x.append('f8') for num in range(8)]

is in fact equal to

[None, None, None, None, None, None, None, None]

but in the process of creating this list of Nones, there is the side effect that x is appended to. So the two results are not in conflict at all.

Zev Chonoles
  • 1,063
  • 9
  • 13
0

In the first case, you are printing the list x, which had 'f8' appended 8 times.

In the second case, you are printing a list (not x) which contains the return value of x.append(...) 8 times. Since append() returns None this is the output you get.

mkrieger1
  • 19,194
  • 5
  • 54
  • 65