0

I want to append words to a list. If I conduct a for loop the answers returned are correct.

However, if I conduct a list comprehension method I get None for the answers. What am I doing wrong?

x=[]
for i in range(0,10):
    x.append('hi'+str(i))
print(x)

Answer : ['hi0', 'hi1', 'hi2', 'hi3', 'hi4', 'hi5', 'hi6', 'hi7', 'hi8', 'hi9']

x= [x.append('hi'+str(i)) for i in range(0,10)]

print(x)

Answer : [None, None, None, None, None, None, None, None, None, None]

zlk2000
  • 53
  • 1
  • 7
  • 4
    What you mean is `x= ['hi'+str(i) for i in range(0,10)]` – Fred Larson May 17 '21 at 15:19
  • 3
    Does this answer your question? [What does "list comprehension" mean? How does it work and how can I use it?](https://stackoverflow.com/questions/34835951/what-does-list-comprehension-mean-how-does-it-work-and-how-can-i-use-it) – ThePyGuy May 17 '21 at 15:21
  • Don't use `x.append` in the list comprehension, just use `"hi"+str(i)`. You just spell out what element makes up the list. The `append` returns nothing (i.e., `None`) and hence you end up with a list full of `None`s. – Robert May 17 '21 at 15:57

2 Answers2

1

You don't need to use append as you are inside the list and append does return None in all cases.

x= ['hi'+str(i) for i in range(0,10)]

print(x)
Mohamed Sayed
  • 491
  • 7
  • 10
1

Your x = [x.append('hi'+str(i)) for i in range(0,10)], build a list with the result of each x.append call, which is None, as it is done inplace, then you erase x with that new list

You want

x = [f"hi{i}" for i in range(10)]
azro
  • 53,056
  • 7
  • 34
  • 70