Add elements to a list inside a list compreension

Asked

Viewed 1,057 times

2

I have following code:

myList = [1,2,3,4,5]
result = []
test = [result.append(i) for i in myList]

whose output from test is:

[None, None, None, None, None]

I’d like to know why, since ex se:

test = [print(i) for i in myList]

Print each one successfully

I don’t want the solution to this, I know in a normal cycle this works, I’d just like to know why the append not be executed as I want

2 answers

3


Because you are adding in the understanding the return of the append function and the function returns None. Example:

>>> print(result.append(i))
None

But the result variable received the 'appendados' values':

>>> print(result)
[1, 2, 3, 4, 5]

0

Take a look at this code, I believe it solves your doubt. :)

data = ['3', '7.4', '8.2']

new_data = [float(n) for n in data]

new_data

[3.0, 7.4, 8.2]

Browser other questions tagged

You are not signed in. Login or sign up in order to post.