-1

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
list_one.extend(list_two)
print(list_one)

# method that doesn't work, gives an output of 'None'
print(list_one.extend(list_two))

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?

1
  • 1
    Because list.extend() returns None. Use concatenation if you need a new list returned. Commented Oct 4, 2019 at 14:08

1 Answer 1

0
print(list_one.extend(list_two))

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
print(list_three)

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.

0

Not the answer you're looking for? Browse other questions tagged or ask your own question.