Why doesn't printing and extending in the same statement work?


I made 2 lists (1 all strings, 1 all integers) using Python 3, tried to print and extend the first list with the other in the same statement, but ultimately got the output of none. Why?

# two lists, each with different data types
list_one = ["cat", "dog", "fish", "eye", "hook"]
list_two = [1, 2, 3, 4, 5]

# method that works and gives the expected output

# method that doesn't work, gives an output of 'None'

Why does the second method give an output of ‘None’ instead of joining the two lists together?

Also, as I’m (very) new to programming, is it messy to put so many functions in a single statement?

Asked By: edememe.noodles




This prints the return value of .extend(). extend has no return value/returns None. This is explicitly done so you’re aware that extend modifies list_one in place, and doesn’t return a new list. So you need to do this as a two-step process: modify the list, then print it.

You could do:

print(list_one + list_two)

This prints the “extended” list immediately, but doesn’t modify either list and also doesn’t store the extended list anywhere. To store the extended list you—again—need a two-step process:

list_three = list_one + list_two

Get used to doing one thing at a time, instead of cramming everything into a single line. Readability is more important than line count. Python follows that doctrine and to some extend enforces it in ways like this.

Answered By: deceze
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.