1

What is the standard way to simulate an array in Python? It seems that the list structure only works well when there are no gaps--and you just keep appending values.

But suppose you wanted to make a hash table and store the values in an array. Depending on your hash function, you might need to store the first value value at index 1456. Would you just start with a list and append 1456 instances of 'None' and then stick in the value? This seems pretty lame and I am wondering if there is a better workaround.

Thanks in advance!

Site
  • 245
  • 3
  • 15

3 Answers3

4

There are a couple of reasonable possibilities.

You can just use a dictionary where the index is the key.

You can use NumPy which add a lot of useful numeric stuff including multi-dimensional arrays

You can use the standard library array modules and just leave gaps

Or you can do as you suggested

What is best for you can likely only be determined by you.

ADD

Now that I think about the, the sparse array from from SciPy not NumPy -- these modules go hand in had, NumPy is useful a lot more often for me.

Gary Walker
  • 8,831
  • 3
  • 19
  • 41
  • the dictionary is a good method - i have used that a few times to convert perl code. not just for sparseness, but also the fact that in python, you have to allocate the array first, but in perl, you can assign anything. e.g. if you have a list `[1, 2]`, in python, `l[3] = 1` returns an IndexError (because it doesn't have a 4th item), but in perl it just extends the list. a dict acts like that too though. – Corley Brigman Jan 11 '14 at 02:27
2

This is highly relevant. A bit more detailed of a response than I could muster up.

Python List vs. Array - when to use?

Community
  • 1
  • 1
mcsilvio
  • 1,098
  • 1
  • 11
  • 20
0

There are three options to 'simulate' arrays in Python:

First option using a normal list, in this case you can just initialize the array as following:

myarray = [None] * arr_size

or using range:

arr = [0 for i in range(arr_size)] 

This will produce a list of my_size size filled with None values. Now you can access what ever index in the valid range without issues.

If you wan a "compact" array (of a specific data type) then you better use array.array module where you have to specify the base type of your array. In the following example the array is initialized by integers.

import array as arr
a = arr.array('i', [0] * arr_size)

You can see more examples on how to use it in the following link

Last option is to use numpy module.

import numpy as np
arr = np.empty(arr_size, dtype=object) 
print(arr)
rkachach
  • 16,517
  • 6
  • 42
  • 66