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:
- Seven steps to compile Python 3.5.0 from source
- Getting started with Python and Anjuta
- Starting up with Python – Part 1 – Numbers and Maths, Variables
- Starting up with Python – Part2 – Modules and Functions, Strings
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