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.
extend
doesn't return a value. Thus, printinga.extend(b)
will beNone
. Thus, if you havea = [5, 6, 7, 8, 9].extend(range(15, 20))
and printa
it will showNone
. A way around it would be to concatenate listsa = [5, 6, 7, 8, 9] + range(15, 20)
[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.[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.