tags:

views:

561

answers:

9

This is an incredibly simple question (I'm new to Python).

I basically want a data structure like a PHP array -- i.e., I want to initialise it and then just add values into it.

As far as I can tell, this is not possible with Python, so I've got the maximum value I might want to use as an index, but I can't figure out how to create an empty list of a specified length.

Also, is a list the right data structure to use to model what feels like it should just be an array? I tried to use an array, but it seemed unhappy with storing strings.

Edit: Sorry, I didn't explain very clearly what I was looking for. When I add items into the list, I do not want to put them in in sequence, but rather I want to insert them into specified slots in the list.

I.e., I want to be able to do this:

list = []

for row in rows:
  c = list_of_categories.index(row["id"])
  print c
  list[c] = row["name"]

Thanks,

Ben

+2  A: 

Use the list constructor, and append your items, like this:

l = list ()
l.append ("foo")
l.append (3)
print (l)

gives me ['foo', 3], which should be what you want. See the documentation on list and the sequence type documentation.

EDIT Updated

For inserting, use insert, like this:

l = list ()
l.append ("foo")
l.append (3)
l.insert (1, "new")
print (l)

which prints ['foo', 'new', 3]

Anteru
Sorry: I didn't really explain what I needed very well. I don't want to append items, but rather insert them into specified slots in the array. I've added more detail to my question.
Ben
+1  A: 

You can use this syntax to create a list with n elements:

lst = [0] * n

But be careful! The list will contain n copies of this object. If this object is mutable and you change one element, then all copies will be changed! In this case you should use:

lst = [some_object() for i in xrange(n)]

Then you can access these elements:

for i in xrange(n):
    lst[i] += 1

A Python list is comparable to a vector in other languages. It is a resizable array, not a linked list.

unbeknown
+2  A: 

http://diveintopython.org/native_data_types/lists.html

You don't need to create empty lists with a specified length. You just add to them and query about their current length if needed.

What you can't do without preparing to catch an exception is to use a non existent index. Which is probably what you are used to in PHP.

Vinko Vrsalovic
Exactly -- the non-existent index is my real problem.
Ben
+4  A: 

If the number of items you want is known in advance, and you want to access them using integer, 0-based, consecutive indices, you might try this:

n = 3
array = n * [None]
print array
array[2] = 11
array[1] = 47
array[0] = 42
print array

This prints:

[None, None, None]
[42, 47, 11]
unwind
+10  A: 

Depending on how you are going to use the list, it may be that you actually want a dictionary. This will work:

d = {}

for row in rows:
  c = list_of_categories.index(row["id"])
  print c
  d[c] = row["name"]

... or more compactly:

d = dict((list_of_categories.index(row['id']), row['name']) for row in rows)
print d

PHP arrays are much more like Python dicts than they are like Python lists. For example, they can have strings for keys.

And confusingly, Python has an array module, which is described as "efficient arrays of numeric values", which is definitely not what you want.

Ned Batchelder
If you want to index the category lists by row name then do: d[row["name"]] = c
PEZ
Ah... this sounds like what I need. I'll give it a try. Thanks!
Ben
Perfect -- that did the job. Thank you!
Ben
@PEZ -- thanks, that's a useful tip as well.
Ben
+1  A: 

Sounds like what you need might be a dictionary rather than an array if you want to insert into specified indices.

dict = {'a': 1, 'b': 2, 'c': 3}
dict['a']

1

Chris Ballance
+1  A: 

I agree with ned that you probably need a dictionary for what you're trying to do. But here's a way to get a list of those lists of categories you can do this:

lst = [list_of_categories.index(row["id"]) for row in rows]
PEZ
+1  A: 

use a dictionary, because what you're really asking for is a structure you can access by arbitrary keys

list = {}

for row in rows:
  c = list_of_categories.index(row["id"])
  print c
  list[c] = row["name"]

Then you can iterate through the known contents with:

for x in list.values():
  print x

Or check if something exists in the "list":

if 3 in list: 
  print "it's there"
Andy Dent
+1  A: 

I'm not sure if I understood what you mean or want to do, but it seems that you want a list which is dictonary-like where the index is the key. Even if I think, the usage of a dictonary would be a better choice, here's my answer: Got a problem - make an object:

class MyList(UserList.UserList):

NO_ITEM = 'noitem'

def insertAt(self, item, index):

    length = len(self)
    if index < length:
        self[index] = item
    elif index == length:
        self.append(item)
    else:
        for i in range(0, index-length):
            self.append(self.NO_ITEM)
        self.append(item)

Maybe some errors in the python syntax (didn't check), but in principle it should work. Of course the else case works also for the elif, but I thought, it might be a little harder to read this way.

Kai