Thursday, December 16, 2010

Python Data Structures

A. List
List is a data structure that so losely like array in PHP or Javascript.

You can instantiate the list:
>>> fnames = ['lady gaga','luna maya','aura kasih'];

Then you can access them by index:
>>> print fnames[0]

Or you can append an element to it like this
>>> fnames.append('tony blair');

To delete an element, use
>>> del fnames[0]

B. Tuples
Tuples is a data structure that fixed. You can add or delete the element of the data at runtime. It's the simplest form of data structure.

To instantiate tuples, you do like this one.
>>> days = ('senin','selasa','rabu','kamis','jumat','sabtu');

Then to access it you use index, like list
>>> print days[0]

C. Dictionaries
This is more complex data structure than the previous one.

To instantiate the data structure, you do like this one
>>> names = {'lady':'gaga','luna':'maya','aura':'kasih'}
>>> city = {5:'denpasar',6:'singapore',9:'palembang'}

To access it, use the key
>>> print names['lady']
>>> print city[5]

In the med step, you can add element by
>>> names['tony'] = 'blair'
>>> city[3] = 'new york'

If you want to delete, use
>>> del names['lady']
>>> del city[5]

Okey, eventually it has finished to give you some introduction to python data structure. It's simple and compact.


No comments:

Post a Comment