Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a built-in function like Perl's splice in Python?

Tags:

python

list

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?

like image 222
user3518094 Avatar asked Apr 20 '14 10:04

user3518094


1 Answers

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.

like image 103
Martijn Pieters Avatar answered Sep 28 '22 05:09

Martijn Pieters