Insertion of last element in Python
Question:
# Code 1
t1 = ['CS', 'IP', 'IT']
t1.insert(len(t1)-1, t1.pop())
print(t1) # output is ['CS', 'IP', 'IT']
# Code 2
t1 = ['CS', 'IP', 'IT']
x = t1.pop()
t1.insert(len(t1)-1, x)
print(t1) # output is ['CS', 'IT', 'IP']
The above two code snippets are similar, yet the output is different. Can someone explain why?
Answers:
In the first scenario len(t1)
is run before t1.pop()
so when list still contains 3 elements. The result of len(t1)-1
is 2 and 'IT'
lands up in third place of list.
In the second one t1.pop()
is run and pops last element from the list so when len(t1)
is run after it returns 2. The whole statement len(t1)-1
returns 1.
Order of operations.
The insert in #1 uses an index of 2 as the length is retrieved before the last element is popped, i.e. IT
is being inserted at index 2 of the list ['CS', 'IP']
.
The insert in #2 inserts at index 1 as the last element of the list has already been popped, i.e. inserting IT
at index 1 of the list ['CS', 'IP']
.
# Code 1
t1 = ['CS', 'IP', 'IT']
t1.insert(len(t1)-1, t1.pop())
print(t1) # output is ['CS', 'IP', 'IT']
# Code 2
t1 = ['CS', 'IP', 'IT']
x = t1.pop()
t1.insert(len(t1)-1, x)
print(t1) # output is ['CS', 'IT', 'IP']
The above two code snippets are similar, yet the output is different. Can someone explain why?
In the first scenario len(t1)
is run before t1.pop()
so when list still contains 3 elements. The result of len(t1)-1
is 2 and 'IT'
lands up in third place of list.
In the second one t1.pop()
is run and pops last element from the list so when len(t1)
is run after it returns 2. The whole statement len(t1)-1
returns 1.
Order of operations.
The insert in #1 uses an index of 2 as the length is retrieved before the last element is popped, i.e. IT
is being inserted at index 2 of the list ['CS', 'IP']
.
The insert in #2 inserts at index 1 as the last element of the list has already been popped, i.e. inserting IT
at index 1 of the list ['CS', 'IP']
.