0

I have a question about list compressions within Python. I am learning through Udacity and uploading my answers/code to an IDE (I could be wrong about it being an IDE) they have through my browser. Before uploading I like to test my code to see if it actually works...as of now I am using Windows Powershell. So the code below is run on Powershell. But my question is...why when I run my code does it print [None, None, None, None] but when I print(new_list) I get ['a','b','c','d']

letters = ['A', 'B', 'C', 'D']
[new_list.append(letter.lower()) for letter in letters]
print(new_list)

When I upload the code to the browser I get a 'Nonetype' object is not an iterable. Makes sense... considering Powershell tells me it is initially viewed as a Nonetype. But, why?

J_Steak
  • 11
  • 1

2 Answers2

1

You are almost there. It should be:

letters = ['A', 'B', 'C', 'D']
new_list = [letter.lower() for letter in letters]
print(new_list)

E.g. have a look here for comparison of list comprehension vs for loop.

The above code snippet with a list comprehension equals to:

letters = ['A', 'B', 'C', 'D']
new_list = list()
for letter in letters:
    new_list.append(letter.lower())
print(new_list)
tbjorch
  • 1,544
  • 1
  • 8
  • 21
  • Oh interesting... I thought you could assign everything to new_list within the list compression. Thank you! – J_Steak Feb 22 '21 at 15:03
  • I mean, of course that is possible, but the point with a list comprehension is to create a new list with a desired content. As myrmica explained in a comment, the append() method doesn't return anythin, hence the list comprehension in your question would result in a list containing only `None` values – tbjorch Feb 22 '21 at 15:06
0

You should be doing something like this:

letters = ['A', 'B', 'C', 'D']
new_list = [letter.lower() for letter in letters]
print(new_list)

The error comes from this line:

[new_list.append(letter.lower()) for letter in letters]

On new_list.append(...) you have not declared the new_list array variable (it doesn't exist), and you're telling it to append something to it.

List comprehensions are a replacement for creating a new list and then appending to it. You create it and populate it in one go

ivanlewin
  • 54
  • 5