Does shifting a value in a list still keep the index value of the shifted element same


#1

Statement-Use the .index(item) function to find the index of “duck”. Assign that result to a variable called duck_index.

Then .insert(index, item) the string “cobra” at that index.
Query-The position of both duck and cobra is same even after inserting cobra in the position of duck.Please verify if insertion option with change the index position value of the shifted value or not


#2

The indices are fixed and never change their order. If an element is shifted it takes on the index of its new location in the list.

>>> animals = ['sparrow', 'duck', 'goose', 'pheasant']
>>> duck_index = animals.index('duck')
>>> duck_index
1
>>> animals.insert(duck_index, 'hawk')
>>> animals.index('duck')
2
>>> 

#3

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.