Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using arrays with other arrays in Python

Trying to find an efficient way to extract all instances of items in an array out of another.

For example

array1 = ["abc", "def", "ghi", "jkl"]

array2 = ["abc", "ghi", "456", "789"]

Array 1 is an array of items that need to be extracted out of array 2. Thus, array 2 should be modified to ["456", "789"]

I know how to do this, but no in an efficient manner.

like image 511
Scott Avatar asked Apr 24 '10 22:04

Scott


People also ask

Can you have an array of arrays in Python?

Practical Data Science using PythonTwo dimensional array is an array within an array. It is an array of arrays. In this type of array the position of an data element is referred by two indices instead of one.

How do you add an array to another array in Python?

If you are using List as an array, you can use its append(), insert(), and extend() functions. You can read more about it at Python add to List. If you are using array module, you can use the concatenation using the + operator, append(), insert(), and extend() functions to add elements to the array.

How do I combine two arrays in Python?

You can use the numpy. concatenate() function to concat, merge, or join a sequence of two or multiple arrays into a single NumPy array. Concatenation refers to putting the contents of two or more arrays in a single array.


1 Answers

These are lists, not arrays. (The word "array" means different things to different people, but in python the objects call themselves lists, and that's that; there are other modules that provide objects that call themselves arrays, such as array and numpy)

To answer your question, the easiest way is to not modify array2 at all. Use a list comprehension:

set1 = set(array1)
array2 = [e for e in array2 if e not in set1]

(the set makes this O(n) instead of O(n^2))

If you absolutely must mutate array2 (because it exists elsewhere), you can use slice assignment:

array2[:] =  [e for e in array2 if e not in set1]

It's just as efficient, but kind of nasty.

edit: as Mark Byers points out, this only works if array1 only contains hashable elements (such as strings, numbers, etc.).

like image 58
Devin Jeanpierre Avatar answered Oct 29 '22 22:10

Devin Jeanpierre