Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is more efficient in python new array creation or in place array manipulation?

Say I have an array with a couple hundred elements. I need to iterate of the array and replace one or more items in the array with some other item. Which strategy is more efficient in python in terms of speed (I'm not worried about memory)?

For example: I have an array

 my_array = [1,2,3,4,5,6]

I want to replace the first 3 elements with one element with the value 123.

Option 1 (inline):

my_array = [1,2,3,4,5,6]
my_array.remove(0,3)
my_array.insert(0,123)

Option2 (new array creation):

my_array = [1,2,3,4,5,6]
my_array = my_array[3:]    
my_array.insert(0,123)

Both of the above will options will give a result of:

>>> [123,4,5,6]

Any comments would be appreciated. Especially if there is options I have missed.

like image 721
Johan Avatar asked Apr 15 '26 11:04

Johan


1 Answers

If you want to replace an item or a set of items in a list, you should never use your first option. Removing and adding to a list in the middle is slow (reference). Your second option is also fairly inefficient, since you're doing two operations for a single replacement.

Instead, just do slice assignment, as eiben's answer instructs. This will be significantly faster and more efficient than either of your methods:

>>> my_array = [1,2,3,4,5,6]
>>> my_array[:3] = [123]
>>> my_array
[123, 4, 5, 6]
like image 53
Daniel G Avatar answered Apr 17 '26 02:04

Daniel G