2

Well, I can easily use this code without errors on Python:

>>>> a = range(5, 10)
>>>> b = range(15, 20)
>>>> a.extend(b)
>>>> a
[5, 6, 7, 8, 9, 15, 16, 17, 18, 19]

I also can use this method, without using b:

>>>> a = range(5, 10)
>>>> a.extend(range(15, 20))
>>>> a
[5, 6, 7, 8, 9, 15, 16, 17, 18, 19]

But I can't figure out why the same thing doesn't happen in this case:

>>>> [5, 6, 7, 8, 9].extend(range(15, 20))
>>>>

Wasn't a supposed to be the same thing as the above list? I only see as difference that I hardcoded the inicial state. I could really understand that the hardcoded list cannot be modified while it's not in a variable or something but...

>>>> [5, 6, 7, 8, 9][2]
7

This surprises me. What is even more strange:

>>>> [5, 6, 7, 8, 7].count(7)
2
>>>> [5, 6, 7, 8, 7].index(8)
3

Why can some list methods work on a hardcoded/not-in-a-variable list, while others can?

I'm not really into using this, that's more for personal knowledge and understanding of the language than usefulness.

1 Answer 1

6
  1. extend doesn't return a value. Thus, printing a.extend(b) will be None. Thus, if you have a = [5, 6, 7, 8, 9].extend(range(15, 20)) and print a it will show None. A way around it would be to concatenate lists a = [5, 6, 7, 8, 9] + range(15, 20)

  2. [5, 6, 7, 8, 9][2] - everything is as should be as it starts counting elements from 0. It is not modifying list, it is merely returning a certain element from the list.

  3. [5, 6, 7, 8, 7].count(7) and [5, 6, 7, 8, 7].index(8) show the expected output. First one is the number of times 7 occurs in the list, second one is an index of number 8 (again, counting starts from 0).

So, all in all the use of hardcoded list behaves as expected in all of the examples you've produced.

Sign up to request clarification or add additional context in comments.

7 Comments

Hmm I understand. Is there any reason for a.extend(b) not return the resulting list besides extending it? I find it useful to use a = [5, 6, 7, 8, 9].extend(range(15, 20)) for example.
@ranisalt [5, 6, 7, 8, 9] + range(15, 20) will do what you want
It is not returning anything because it is an operation on the list. You attach elements to 'a' when you do 'a.extend'. Conceptually, it would be bad to make this operation do two things - return extended list AND extend the passed list.
@sashkello a = [5, 6, 7, 8, 9].extend(range(15, 20)) results in a being None.
@flornquake Yes, that's right and this is what I say in the very first paragraph of my answer.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.