I would think that if i did the following code in python
var = [0].extend(range(1,10))
then var would be a list with the values 0 – 9 in it.
What gives?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
As Oscar López and others have already explained, extend is a command, which returns None, to abide by command/query separation.
They’ve all suggested fixing this by using extend as a command, as intended. But there’s an alternative: use a query instead:
It’s important to understand the difference here.
extendmodifies your[0], turning it into[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]. But the+operator leaves your[0]alone, and returns a new list[0, 1, 2, 3, 4, 5, 6, 7, 8, 9].In cases where you’ve got other references to the list and want to change them all, obviously you need
extend.However, in cases where you’re just using [0] as a value, using
+not only allows you to write compact, fluid code (as you were trying to), it also avoids mutating values. This means the same code works if you’re using immutable values (like tuples) instead of lists, but more importantly, it’s critical to a style of functional programming that avoids side effects. (There are many reasons this style is useful, but one obvious one is that immutable objects and side-effect-free functions are inherently thread-safe.)