I am trying to find a way to find/replace elements from list other than using iteration like there is a function splice() in perl.
@a = splice(@list,2,3,(1,1,1));
print @a;
In python we need to go through loop and find and the replace. This is looking bit time consuming. So is there any way to replace like we do in Perl?
You can use slice assignment:
somelist[2:5] = [1, 1, 1]
This takes the elements 2, 3 and 4, replacing them with the new list. The new list doesn't have to be the same length, or can be empty. The slice you assign to can be of length 0 too, effectively inserting the right-hand sequence into the target list.
Demo:
>>> a = [1, 2, 3]
>>> a[1:1] = [4, 5, 6]
>>> a
[1, 4, 5, 6, 2, 3]
>>> b = ['foo', 'bar', 'baz', 'spam', 'ham', 'eggs']
>>> b[2:5] = [1, 1, 1]
>>> b
['foo', 'bar', 1, 1, 1, 'eggs']
>>> c = [42, 38, 22]
>>> c[:2] = []
>>> c
[22]
Slice assignment covers all the same use cases the Perl splice()
function supports.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With