Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
659 views
in Technique[技术] by (71.8m points)

python - .extend() method returning 'None' and not the desired combination of lists I intended it to return

I am playing around with some basic python methods. Right now I am experimenting with the .extend() method. I basically have two lists and want to combine them into one larger list for demonstration purposes. This works successfully (successfully as in returning the extended list) in the Shell environment, but not when saving the program. When I want to save the program and run it, it returns the value of 'None'. Any assistance would be greatly appreciated. Thank you.

listOne=[1,2,3]

listTwo=[4,5,6]

listOneandlistTwo=listOne.extend(listTwo)

print(listOneandlistTwo)
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
listOneandlistTwo=listOne.extend(listTwo)

extend() extends the given list but returns None*, so you have extended listOne with the contents of listTwo and assigned None to listOneandListTwo.

What you want (assuming you want to leave listOne and listTwo as they are) is this:

listOneandlistTwo = listOne + listTwo

* This behavior is by design. If extend() returned the extended list, would it return a copy that's extended? Or would it return the original list extended? It's another detail to remember, so by returning None you are meant to think, "oh, since it's returning None it must be extending the list in place, otherwise it'd be useless."


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...