Monday, March 5, 2012

Sequences and Listing


In this post I will discuss an interesting thing about Python known as Sequences and Listings


Sequences are something that lets us store data or elements, or you can say its a list of elements. And the elements can be a Strings or Integers

Okay so let me show you how to create a List.

As usual open the IDLE.

To create a List, first we have to type in a name for the List, and then assign elements to it, and elements are typed within square brackets.

Example:

>>>
>>> family = ['dog','bro','dad','mom','sis']
>>>

Here the Elements 'dog','bro','dad','mom','sis' are stored in a List named family. We can add as many elements we want in a list.

Now pay a close attention here, when we create a List, Python automatically assigns an index number to each element, and the index number starts with zero. So here for this list, the indexing(numbering) that python does for each element is:

'dog' = 0
'bro' = 1
'dad' = 2
'mom' = 3
'sis' = 4

So here in this family list, though we have 5 elements but the counting starts with 0 through 4.


So after the list is created, we can extract out the elements from the List by pointing the index number. So suppose we wanted to extract dog, or rather print the word dog from the list, we have to type.

Syntax: family[index number of the dog]

>>> family[0]
'dog'
>>>

Here comes another interesting thing, for people who likes to read backwards...Python made it easy for them...

So When a list a created in Python, the numbering is two ways, and is correct either way the user is comfortible. One way which was from left to right, and starts with 0, i have already mentioned above. Now lets see how python does a backward indexing, from right to left.

When you go from right to left, the numbering starts with -1, -2, -3 and so on...

So in the family List...

'dog' = -5
'bro' = -4
'dad' = -3
'mom' = -2
'sis' = -1

So, the list is indexed in this way by Python:

'dog' = 0 or -5
'bro' = 1 or -4
'dad' = 2 or -3
'mom' = 3 or -2
'sis' = 4 or -1


So if we want to display 'sis' from the list, we can either either

>>> family [4]
'sis'
>>> family [-1]
'sis'

So now we know how to create a list, and also how to display an exact element from the list with the index numbers.

The same goes strings. Suppose we have a word sumthing like this:

>>> 'python'[3]
'h'
>>>

This displayed 'h', because the index number of h is 3. And also this is correct.

>>> 'python'[-3]
'h'
>>>

Because if we count backwards, the index number of 'h' is -3


So i hope this was informative for you, practice it, know how it works, as it is a very important topic in python, and will be used in most cases in future posts with programmings.

Thank You!

1 comments: