14

I want to populate an array in python so that I can use id numbers to index into the array. Not all indexes will exist in the array and items will not necessarily be added to the array in order. The largest possible index is not known (or at least I'd prefer not to hard code it). Is there a way to dynamically grow the array when assigning? I.e I want something like

arr = []
for x in xs
    arr[x.index] = x

but this gives "IndexError: list assignment index out of range". I tried using list.insert() but that does not work if the items are not inserted in order, as it changes the index of items already in the array.

Is there a good way to do this in python, or do I have to settle for initializing the array "big enough"?

3

4 Answers 4

12

You need a dictionary

arr = {}
for x in xs:
    arr[x.index] = x

If all you are going to do is to build the dictionary, you can use dictionary comprehension like this

myDict = {x.index:x for x in xs}
Sign up to request clarification or add additional context in comments.

5 Comments

tengfred: Dictionaries would be good a sparsely populated dataset of unknown size. However, unlike an array (or list), its contents are unordered which means iterating through them in order isn't possible -- but that may not matter if you only access them via x.index.
A dictionary seems like it would work, although my dataset is pretty dense. On the other hand, performance is not critical, so it will probably be good enough.
@martineau, there is always the OrderedDict that can be used to retain order between, say, an original dataset and the derived dictionary. In this case, you would change your declaration to: from collections import OrderedDict; arr = OrderedDict(). However, you can not use list comprehension to construct the OrderedDict.
@KeithHanlan: Actually dictionaries started unofficially maintaining order in Python 3.6, and officially in 3.7+, so that could make the point moot. Also, it is possible create an OrderedDict with a list comprehension—in fact, it's the recommended way (or at least was a some point).
Thanks for the information @martineau. It will be nice not to have to import OrderedDict. I look forward to being able to migrate to 3.7 (especially for f-strings). And I was mistaken about list compression: in my experimentation, I failed to use the correct in cantation. Thanks for the correction.
8

Python arrays can grow dynamically, but simply assigning to an index does not extend the array.

Arrays have the extend method for adding a bunch of items at once from a collection. For example:

>>> a = [1, 2, 3]
>>> a.extend([None, None])
>>> a
[1, 2, 3, None, None]

You can emulate auto-extending array assignment like this:

def arr_assign(arr, key, val):
    try:
        arr[key] = val
        return
    except IndexError:
        # Do not extend the array for negative indices
        # That is ridiculously counterintuitive
        assert key >= 0
        arr.extend(((key + 1) - len(arr)) * [None])
        arr[key] = val
        return

For example:

>>> a = []
>>> arr_assign(a, 4, 5)
>>> a
[None, None, None, None, 5]

As an addendum, languages that do have the auto-extend behavior by default (e.g. Perl, Ruby, PHP, JavaScript, Lua) tend to be less strict than Python and will return a magical null value if you access a slot in an array that doesn't exist. This means that they can allow auto-extending when assigning to a non-existent index without changing the behavior of the array at any other index.

E.g. In Ruby a[2] doesn't change despite the fact that a has changed underneath it.

irb(main):006:0> a = []
=> []
irb(main):007:0> a[2]
=> nil
irb(main):008:0> a[4] = 7
=> 7
irb(main):009:0> a
=> [nil, nil, nil, nil, 7]
irb(main):010:0> a[2]
=> nil

Comments

0
x = []
ch=int(input("How many values you want to add in an array"))
for i in range(ch):
    z=int(input("Enter value for array"))
    x.append(z) #now u r pushing value of Z entered by you at run time
print(x)

1 Comment

The question is not about plainly inserting values, but structures containing indexes and values
-1

why dont you try appending the list?

arr = []
for x in xs
    arr.append(x)

then access arr as : arr[0], arr[1] and so on..

1 Comment

Hi! I think the reason you got down votes on this thread (and it wasn't from me) is because the answer didn't follow the requirements of the question. Check Faust's answer to learn a bit more about the proper format. I liked your approach to the problem, please adjust your answer and undeleted when its ready. Good luck!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.