Arrays in python
Alex Martelli
aleaxit at yahoo.com
Sat Sep 2 15:30:16 EDT 2000
More information about the Python-list mailing list
Sat Sep 2 15:30:16 EDT 2000
- Previous message (by thread): Arrays in python
- Next message (by thread): REQ: ICQ messages in Python
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
"Marcus" <talos at algonet.se> wrote in message news:39B1467D.9CA098FC at algonet.se... > Hello, I am but a beginner in the language and I have a small question. > Python seem to have a strange syntax concerning arrays (atleast for a C > programmer). The Python array module only holds homogeneous arrays of elementary types, not object instances. So, for your purpose, you're more likely to want a Python *list* (which is a builtin Python type), not a Python *array* (as supplied by the array module, with "import array"). > What i wanna do is simply something like: > > array[0] = open("/home/talos/somefile"); To be able to do this, array must be a list with 1 or more elements (not an empty list). There are many ways to make it so, such as array = [None] a 1-element list with a value of None. After that, you can write the above assignment (the final semicolon is accepted, though it's not required and no Python programmer would dream of using it). > and then be able to use it like so: > > line = array[0].readline; This would set 'line' to the *function* ("bound method") readline of the file object -- exactly like in C. Exactly like in C, if you want to *CALL* that function (and set "line" to the RESULT of the call), you need to add parentheses: line = array[0].readline() Don't tell me that the need to use parentheses to call a function (rather than just taking a reference to it) is "strange syntax ... for a C programmer"?! It's ALWAYS been like that in C. > print line,; You can do that (again, the ending semicolon is peculiar, but if you insist you are allowed to use it in Python). > How is this done in python? Binding the 'array' variable to a list of 1 or more elements, which is all you need to add "array"-wise to your code, can be done in many ways, depending on how long you want the list to be and what initial elements you want to be there. For a dummy-initial-elements list of N elements, for example, the most natural idiom is: array=[None]*N If you want to start with an EMPTY list, array=[] but then you can't refer to a 0-th element until you add it, e.g. with the append method: array.append(open("/a/file")) Alex
- Previous message (by thread): Arrays in python
- Next message (by thread): REQ: ICQ messages in Python
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
More information about the Python-list mailing list