0

I have a list of Tuples that I want to print in Jupyter Notebooks. My code prints them correctly but seems to be printing a strange line at the end '[None,None,None]', I can't figure out why.

If I swap the list comprehension code with a for loop to print the same thing I don't get the '[None,None,None]' line. But I'm trying to write more easy to read code and would prefer to keep the list comprehension approach, there is definitely something I can learn from this mistake.

Check error message and code in the attached image

a = [(1, 108460.7476635514), (2, 103072.89682539682), (3, 77251.9265944645)]
[print('Group=', x[0], '; Avg=', x[1]) for x in a]
nu2222
  • 3
  • 2
  • 1
    You are adding print inside list comprehension which returns None. Remove print and you'll get the tuple you are looking for – Moinuddin Quadri Feb 03 '21 at 23:02
  • Use a proper loop to print your data. List comprehension with side effects is not Pythonic. – Asocia Feb 03 '21 at 23:03
  • @Asocia I disagree with your statement. List Comprehension are completely Pythonic. One just needs to use them right. List Comprehension are actually one of the most Pythonic things – Moinuddin Quadri Feb 03 '21 at 23:07
  • 1
    I think @Asocia means that list comprehension should be used only for creating lists in Python, not solely for repeating a process that doesn't need to generate a list. List comprehension is Pythonic but misusing list comprehension isn't. – Andrew Mascillaro Feb 03 '21 at 23:09
  • @Anonymous What Andrew said is right. If you are not using the list anywhere in your program then don't create it. Here is a helpful [link](https://stackoverflow.com/q/5753597/9608759). – Asocia Feb 04 '21 at 07:05
  • I know that if one doesn't need something, we should not do it. It is applicable for everything, but that doesn't makes List Comprehension non Pythonic. Use-case wasn;t right makes more sense – Moinuddin Quadri Feb 04 '21 at 08:11
  • @Anonymous I didn't say list comprehension is not Pythonic. I said list comprehension *with side effects* is not Pythonic. Maybe a better wording would be "using list comprehension *only* for its side effects is not Pythonic." – Asocia Feb 04 '21 at 09:06

1 Answers1

0

Jupyter notebooks return the value of the last variable in a code cell if there is no assignment operator (=) in the last statement. This code outputs the value of the list (the return value of all print statements, or None) because you're creating a list during list comprehension. Generally, it is bad practice to use list comprehension if you're not going to use the list it generates. The cleaner, more Pythonic way to do this is via a standard for loop:

a = [(1, 108460.7476635514), (2, 103072.89682539682), (3, 77251.9265944645)]
for i in a:
    print('Group=', x[0], '; Avg=', x[1])
  • Thanks, that makes sense. I see that I shouldn't have tried to print within the list comprehension and should've just generated the tuple. – nu2222 Feb 03 '21 at 23:28