How can I write and call on arrays in python?

I want to be able to do this....

nameofarray1 = (1, 2, 1, 5, 6, 3, 2, 6, 8, 9),
(4, 4, 3, 5, 7, 5, 5, 6, 8, 1),
....... and so on

and then later read from it by saying something such as...

if namofarray[xcooridinate, ycooridinate] == 2:
.............do something...........

So basically read the array by using x and y coordinates to search the array

Its probably pretty simple but I am getting errors on everything I try so..... Thanks and please try to help!

Recommended Answers

All 2 Replies

In Python you have two choices: Lists or Tuples. The main difference is that lists are mutable and tuples are immutable. Here is how you use them:

Lists

You can declare a list two ways:

myList = []

or,

myList = [1,3,5]

You can only declare a tuple by adding to it, since it is not mutable.

myTuple = ("a string", 7)

You cannot decalare a tuple like a list this way:

myTuple = ()

You reference a list and a tuple the same way:

print myTuple[0]

print myList[0]

Since lists are mutable you can delete or assign different values to current elements:

myList[0] = "another string"
del myList [0]

You can append to lists this way:

myList.append("still another string")

You may not delete a tuple item, they are immutable:

del myTuple[0]

One other thing worth mentioning is a slice. You can get a sub list from list or tuple this way:

x = myList[0:3]

The previous will get elements 0 through 3.

If you don't have a number for the first spot, it will assume zero:

x = myList[:3]

If you don't have a number for the second spot, it will assume you mean to go to the end:

x = myList[2:]

If you want to referenct just the last element tell it to go one from the end this way:

myList[-1]

If you want to ference the element nine from the end, this way:

myList[-9]

You can use the same notation for slices:

myList[:-2]

It will get all elements from the beginning up to the last two.

For a 2D array, a list-of-lists can work:

>>> a = [[1,2,3],[4,5,6],[7,8,9]]
>>> a[1][2]
6
>>>

Jeff

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.