Reputation: 379
I have some basic code that I'm not grasping the behaviour of:
L = [ 'a', 'bb', 'ccc' ]
L.append(range(2))
print len(L)
print len(L + range(1))
print len(L)
The output of which is
4
5
4
This is confusing to me, as my thought process is that the length of the initial list is 3, and appending range(2)
to the end brings it to length of 5. Therefore I'd expect the output to be 5 6 5
. I'm sure it's a simple quirk, but I'm a bit lost and having a hell of a time trying to find an answer online. Would anyone be able to point me in the right direction?
Upvotes: 14
Views: 59250
Reputation: 1486
g=[1,2,3,4,7,8]
z=[5,6]
def insertRange(start,YourList,anotherlist):
if isinstance(YourList,list) and isinstance(anotherlist,list) :
YourlistPart1=YourList[0:start]
YourlistPart2=YourList[start:]
YourlistPart1.extend(anotherlist)
YourlistPart1.extend(YourlistPart2)
print(YourlistPart1)
insertRange(4,g,z)
You can't insert range in a specific location in python but you can work around by function using extend you can split your list extend first part and then merge the 2 lists again start= doesn't start from 0 if you wish to start insert from index 3 which = 4 in the example you start with 3
summary
start from 1 adds the list after the index 0 and shift the other elements
start from 4 adds the list after the index 3 and shift the other elements
start from 5 adds the list after the index 4
Upvotes: 0
Reputation: 1121416
You appended a single list object. You did not add the elements from the list that range
produces to L
. A nested list object adds just one more element:
>>> L = ['a', 'bb', 'ccc']
>>> L.append(range(2))
>>> L
['a', 'bb', 'ccc', [0, 1]]
Note the [0, 1]
, the output of the range()
function.
You are looking for list.extend()
instead:
>>> L = ['a', 'bb', 'ccc']
>>> L.extend(range(2))
>>> L
['a', 'bb', 'ccc', 0, 1]
>>> len(L)
5
As an alternative to list.extend()
, in most circumstances you can use +=
augmented assignment too (but take into account the updated L
list is assigned back to L
, which can lead to surprises when L
was a class attribute):
>>> L = ['a', 'bb', 'ccc']
>>> L += range(2)
>>> L
['a', 'bb', 'ccc', 0, 1]
Upvotes: 28