Starting up with Python – Part3

Moving on to the part 3 of my article on Learning Python, I have now reached Sequences and List. It’s indeed a vast python world. Previous articles are as follows:

5. Sequences and List

There are six sequence types: strings, Unicode strings, lists, tuples, buffers, and xrange objects. To create a list, we first give the list a name. For example family = [‘mom’, ‘dad’, ‘sister’, ‘brother’, ‘cat’] Each element within the list is associated with a number starting by 0. It is also counted backward with negative numbers.

>>> family = ['mom', 'dad', 'sister', 'brother', 'cat']
 >>> family[0]
 'mom'
 >>> family[1]
 'dad'
 >>> family [-5]
 'mom'
 >>> family [-1]
 'cat'

You can also extract characters from a string as c is referenced as number 2

>> 'hackers' [2]
 'c'

6. Slicing

Lets now extract a slice of a sequence. You can slice information from a sequence in a backward sequence too. When slicing you need two values. If no values are given, it gives you the whole sequence.

> example = [0,1,2,3,4,5,6,7,8,9]
 >>> example [4:8]
 [4, 5, 6, 7]
 >>> example [4:9]
 [4, 5, 6, 7, 8]
 >>> example [4:10]
 [4, 5, 6, 7, 8, 9]
 >>> example [-5:]
 [5, 6, 7, 8, 9]
>> example [:]
 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9

You can also extract information using 3 values that is the starting number, the ending number and the optional number [How many numbers you want to skip before getting to the last one] example [1:8:2]

> example [1:8:2]
 [1, 3, 5, 7]
>>> example [::-2]
 [9, 7, 5, 3, 1]

7.Editing

Sequences, unlike, strings can also be concatenated. By creating two sequences and using the + sign in between to get it concatenated.

>> [7,4,5]+[4,6,5]
 [7, 4, 5, 4, 6, 5]

You can also multiply strings and sequences

>> 'HackersMauritius' * 2
 'HackersMauritiusHackersMauritius'
>> [100]* 2
 [100, 100]

You can also check for characters in a name example. Is there the letter Z in hackersMauritius ?

name ='HackersMauritius'
 >>> 'z' in name
 False
 >>> 'a' in name
 True

I can also check for elements in a sequence

> family = ['mom', 'dad', 'sister', 'brother', 'cat']
 >>> 'dog' in family
 False
 >>> 'cat' in family
 True
Nitin J Mutkawoa https://tunnelix.com

Blogger at tunnelix.com | Founding member of cyberstorm.mu | An Aficionado Journey in Opensource & Linux – And now It's a NASDAQ touch!

You May Also Like

More From Author