How to replace two elements in a list with single element in Python?
For example:
list_a = [1, 2, 3, 4, 5, 6, 7]
if I wanted to replace 2 and 3 with let's say 9 and I only know the indices, (I don't know the values)
list_a = [1, 9, 4, 5, 6, 7]
How to replace two elements in a list with single element in Python?
For example:
list_a = [1, 2, 3, 4, 5, 6, 7]
if I wanted to replace 2 and 3 with let's say 9 and I only know the indices, (I don't know the values)
list_a = [1, 9, 4, 5, 6, 7]
IIUC, you could use a slice and assign your value as list:
list_a = [1, 2, 3, 4, 5, 6, 7]
list_a[1:3] = [9] # list_a[1:3] are elements [2, 3]
print(list_a)
Output: [1, 9, 4, 5, 6, 7]
Note that in python the indices start with 0
, thus your slice is 1:3
(indices 1 to 3, excluding 3), see How slicing in Python works for more details.
# indices: 0 1 2 3 4 5 6
list_a = [1, 2, 3, 4, 5, 6, 7]
# slice: x x
we can use the list slicing method
list_a = [1, 2, 3, 4, 5, 6, 7]
# here you want to eliminate 2,3 elements and replace 9 instead of them
index= list_a.index(2)
# Syntax: l=l[:index]+[‘new_value’]+l[index+2:]
list_a = list_a[ :index] + [9] + list_a[index+2: ]
print(list_a)
Output:
[1, 9, 4, 5, 6, 7]
You can use list slices to solve your problem. Example code:
#Create your list
list_a = [1, 2, 3, 4, 5, 6, 7]
#Replace the elements from index 1 to 3 i.e. 2nd to 4th element with 9
list_a[1:3] = [9]
Then you can print the list:
print(list_a)
Output:
[1, 9, 4, 5, 6, 7]
Note that you have to put 9 within square brackets. This is because you can replace multiple elements only with an iterable. So, putting nine within square brackets, makes it an iterable object. Not putting 9 within brackets will give a TypeError.