Let us say, we have a List that contains three names, 'Mohan', 'Kriti' and 'Salim'. And we want to replace the name 'Kriti' with a new name 'Paul'.
x = ["Mohan", "Kriti", "Salim"] x[1] = "Paul" print(x)
So, in the above code we have created a 'List' and initialised to the variable 'x'.
Now, let us see, how the values are positioned in the List
Now, if we see the above diagram, 'Kriti' resides at position/index '1'. So, what we do is,just replace the position/index '1' (i.e. x[1]) with the new name 'Paul'.
And we get the below output,
Let us take the same example, in which we have a List that contains three names, 'Mohan', 'Kriti' and 'Salim'. And we want to replace the name 'Kriti' with a List with another List that has two names, 'Rishav' and 'Rishav'.
x = ["Mohan", "Kriti", "Salim"] x[1] = ["Rishav","Rishav"] print(x)
So, in the above code we have created a 'List' and initialised to the variable 'x'.
Now, let us see, how the values are positioned in the List
Now, if we see the above diagram, 'Kriti' resides at position/index '1'. So, what we do is,just replace the position/index '1' (i.e. x[1]) with the new List that has two names, 'Rishav' and 'Rishav'.
And we get the below output,
Let us say, we have a List that contains five names, 'Mohan', 'John', 'Paul', 'Kriti' and 'Salim'. And this time we want to replace the names 'John', 'Paul' and 'Kriti' with a new names, 'Anwar', 'Mitali' and 'Anjana'.
x = ["Mohan", "John", "Paul", "Kriti", "Salim"] x[1:4] = ["Anwar", "Mitali", "Anjana"] print(x)
So, in the above code we have created a 'List' and initialised to the variable 'x'.
In the below way the values are positioned in the List,
Now, if we see the above diagram, 'John' resides at position/index '1', 'Paul' in '2' and 'Kriti' in position/index '3'.
So, what we do is, specify the range, 1 to 4 in 'x[1:4]' and assign new values, 'Anwar','Mitali' and 'Anjana'.
And, 'John', 'Paul' and 'Kriti' gets replaced with 'Anwar', 'Mitali' and 'Anjana'.
And the List with replaced values is,
And we get the below output,