Python has six built-in types of sequences. i will concentrates on two of the most common ones: lists and tuples. The other built-in sequence types are strings (which I revisit in the next chapter), Unicode strings, buffer objects, and xrange objects.
The main difference between lists and tuples is that you can change a list, but you can’t change a tuple. This means a list might be useful if you need to add elements as you go along, while a tuple can be useful if, for some reason, you can’t allow the sequence to change. Reasons
for the latter are usually rather technical, having to do with how things work internally in Python. That’s why you may see built-in functions returning tuples. For your own programs, chances are you can use lists instead of tuples in almost all circumstances Sequences are useful when you want to work with a collection of values. You might have a sequence representing a person in a database, with the first element being their name, and the second their age. Written as a list (the items of a list are separated by commas and enclosed in square brackets), that would look like this:
>>> edward = ['Edward Gumby', 42]
But sequences can contain other sequences, too, so you could make a list of such persons,
which would be your database:
>>> edward = ['Edward Gumby', 42]
>>> john = ['John Smith', 50]
>>> database = [edward, john]
>>> database
[['Edward Gumby', 42], ['John Smith', 50]]
Note Python has a basic notion of a kind of data structure called a container, which is basically any object that can contain other objects. The two main kinds of containers are sequences (such as lists and tuples) and mappings (such as dictionaries)
Common Sequence Operations
There are certain things you can do with all sequence types. These operations include indexing, slicing, adding, multiplying, and checking for membership. In addition, Python has built-in functions for finding the length of a sequence, and for finding its largest and smallest elements.
Indexing
All elements in a sequence are numbered—from zero and upwards. You can access them individually with a number, like this:
>>> greeting = 'Hello'
>>> greeting[0]
Note: A string is just a sequence of characters. The index 0 refers to the first element, in this case the letter H.
'H'
This is called indexing. You use an index to fetch an element. All sequences can be indexed in this way. When you use a negative index, Python counts from the right; that is, from the last element.
The last element is at position –1 (not –0, as that would be the same as the first element):
>>> greeting[-1]
'o'
String literals (and other sequence literals, for that matter) may be indexed directly, without using a variable to refer to them. The effect is exactly the same:
>>> 'Hello'[1]
'e'
If a function call returns a sequence, you can index it directly. For instance, if you are simply interested in the fourth digit in a year entered by the user, you could do something like this:
>>> fourth = raw_input('Year: ')[3]
Year: 2005
>>> fourth
'5'
Slicing
Just as you use indexing to access individual elements, you can use slicing to access ranges of elements. You do this by using two indices, separated by a colon:
>>> tag = '<a href="http://www.python.org">Python web site</a>'
>>> tag[9:30]
'http://www.python.org'
>>> tag[32:-4]
'Python web site'
As you can see, slicing is very useful for extracting parts of a sequence. The numbering here is very important. The first index is the number of the first element you want to include. However, the last index is the number of the first element after your slice. Consider the following:
>>> numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> numbers[3:6]
[4, 5, 6]
>>> numbers[0:1]
[1]
In short, you supply two indices as limits for your slice, where the first is inclusive and the second is exclusive.
Let’s say you want to access the last three elements of numbers (from the previous example).
You could do it explicitly, of course:
>>> numbers[7:10]
[8, 9, 10]
This is fine, but what if you want to count from the end?
>>> numbers[-3:-1]
[8, 9]
It seems you cannot access the last element this way. How about using 0 as the element “one step beyond” the end?
>>> numbers[-3:0]
[]
Luckily, you can use a shortcut: if the slice continues to the end of the sequence, you may simply leave out the last index:
>>> numbers[-3:]
[8, 9, 10]
The same thing works from the beginning:
>>> numbers[:3]
[1, 2, 3]
In fact, if you want to copy the entire sequence, you may leave out both indices:
>>> numbers[:]
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Adding Sequences
Sequences can be concatenated with the addition (plus) operator:
>>> [1, 2, 3] + [4, 5, 6]
[1, 2, 3, 4, 5, 6]
>>> 'Hello, ' + 'world!'
'Hello, world!'
>>> [1, 2, 3] + 'world!'
Traceback (innermost last):
File "<pyshell#2>", line 1, in ?
[1, 2, 3] + 'world!'
TypeError: can only concatenate list (not "string") to list As you can see from the error message, you can’t concatenate a list and a string, although both are sequences. In general, you cannot concatenate sequences of different types.
Multiplication
Multiplying a sequence by a number x creates a new sequence where the original sequence is repeated x times:
>>> 'python' * 5
'pythonpythonpythonpythonpython'
Membership
To check whether a value can be found in a sequence, you use the in operator. This operator is a bit different from the ones discussed so far (such as multiplication or addition). It checks whether something is true and returns a value accordingly: True for true and False for false. Such operators
are called Boolean operators, and the truth values are called Boolean values.
Here are some examples that use the in operator:
>>> permissions = 'rw'
>>> 'w' in permissions
True
>>> 'x' in permissions
False
>>> users = ['mlh', 'foo', 'bar']
>>> raw_input('Enter your user name: ') in users
Enter your user name: mlh
True
>>> subject = '$$$ Get rich now!!! $$$'
>>> '$$$' in subject
True
However, the only members or elements of a string are its characters. So, the following makes perfect sense:
>>> 'P' in 'Python'
True
Length, Minimum, and Maximum
The built-in functions len, min, and max can be quite useful. The function len returns the number of elements a sequence contains. min and max return the smallest and largest element of the sequence, respectively. (You learn more about comparing objects in Chapter 5, in the section
“Comparison Operators.”)
>>> numbers = [100, 34, 678]
>>> len(numbers)
3
>>> max(numbers)
678
>>> min(numbers)
34
>>> max(2, 3)
3
>>> min(9, 3, 2, 5)
2
How this works should be clear from the previous explanation, except possibly the last two expressions. In those, max and min are not called with a sequence argument; the numbers are supplied directly as arguments.
>>> [42] * 10
[42, 42, 42, 42, 42, 42, 42, 42, 42, 42]
The main difference between lists and tuples is that you can change a list, but you can’t change a tuple. This means a list might be useful if you need to add elements as you go along, while a tuple can be useful if, for some reason, you can’t allow the sequence to change. Reasons
for the latter are usually rather technical, having to do with how things work internally in Python. That’s why you may see built-in functions returning tuples. For your own programs, chances are you can use lists instead of tuples in almost all circumstances Sequences are useful when you want to work with a collection of values. You might have a sequence representing a person in a database, with the first element being their name, and the second their age. Written as a list (the items of a list are separated by commas and enclosed in square brackets), that would look like this:
>>> edward = ['Edward Gumby', 42]
But sequences can contain other sequences, too, so you could make a list of such persons,
which would be your database:
>>> edward = ['Edward Gumby', 42]
>>> john = ['John Smith', 50]
>>> database = [edward, john]
>>> database
[['Edward Gumby', 42], ['John Smith', 50]]
Note Python has a basic notion of a kind of data structure called a container, which is basically any object that can contain other objects. The two main kinds of containers are sequences (such as lists and tuples) and mappings (such as dictionaries)
Common Sequence Operations
There are certain things you can do with all sequence types. These operations include indexing, slicing, adding, multiplying, and checking for membership. In addition, Python has built-in functions for finding the length of a sequence, and for finding its largest and smallest elements.
Indexing
All elements in a sequence are numbered—from zero and upwards. You can access them individually with a number, like this:
>>> greeting = 'Hello'
>>> greeting[0]
Note: A string is just a sequence of characters. The index 0 refers to the first element, in this case the letter H.
'H'
This is called indexing. You use an index to fetch an element. All sequences can be indexed in this way. When you use a negative index, Python counts from the right; that is, from the last element.
The last element is at position –1 (not –0, as that would be the same as the first element):
>>> greeting[-1]
'o'
String literals (and other sequence literals, for that matter) may be indexed directly, without using a variable to refer to them. The effect is exactly the same:
>>> 'Hello'[1]
'e'
If a function call returns a sequence, you can index it directly. For instance, if you are simply interested in the fourth digit in a year entered by the user, you could do something like this:
>>> fourth = raw_input('Year: ')[3]
Year: 2005
>>> fourth
'5'
Slicing
Just as you use indexing to access individual elements, you can use slicing to access ranges of elements. You do this by using two indices, separated by a colon:
>>> tag = '<a href="http://www.python.org">Python web site</a>'
>>> tag[9:30]
'http://www.python.org'
>>> tag[32:-4]
'Python web site'
As you can see, slicing is very useful for extracting parts of a sequence. The numbering here is very important. The first index is the number of the first element you want to include. However, the last index is the number of the first element after your slice. Consider the following:
>>> numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> numbers[3:6]
[4, 5, 6]
>>> numbers[0:1]
[1]
In short, you supply two indices as limits for your slice, where the first is inclusive and the second is exclusive.
Let’s say you want to access the last three elements of numbers (from the previous example).
You could do it explicitly, of course:
>>> numbers[7:10]
[8, 9, 10]
This is fine, but what if you want to count from the end?
>>> numbers[-3:-1]
[8, 9]
It seems you cannot access the last element this way. How about using 0 as the element “one step beyond” the end?
>>> numbers[-3:0]
[]
Luckily, you can use a shortcut: if the slice continues to the end of the sequence, you may simply leave out the last index:
>>> numbers[-3:]
[8, 9, 10]
The same thing works from the beginning:
>>> numbers[:3]
[1, 2, 3]
In fact, if you want to copy the entire sequence, you may leave out both indices:
>>> numbers[:]
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Adding Sequences
Sequences can be concatenated with the addition (plus) operator:
>>> [1, 2, 3] + [4, 5, 6]
[1, 2, 3, 4, 5, 6]
>>> 'Hello, ' + 'world!'
'Hello, world!'
>>> [1, 2, 3] + 'world!'
Traceback (innermost last):
File "<pyshell#2>", line 1, in ?
[1, 2, 3] + 'world!'
TypeError: can only concatenate list (not "string") to list As you can see from the error message, you can’t concatenate a list and a string, although both are sequences. In general, you cannot concatenate sequences of different types.
Multiplication
Multiplying a sequence by a number x creates a new sequence where the original sequence is repeated x times:
>>> 'python' * 5
'pythonpythonpythonpythonpython'
Membership
To check whether a value can be found in a sequence, you use the in operator. This operator is a bit different from the ones discussed so far (such as multiplication or addition). It checks whether something is true and returns a value accordingly: True for true and False for false. Such operators
are called Boolean operators, and the truth values are called Boolean values.
Here are some examples that use the in operator:
>>> permissions = 'rw'
>>> 'w' in permissions
True
>>> 'x' in permissions
False
>>> users = ['mlh', 'foo', 'bar']
>>> raw_input('Enter your user name: ') in users
Enter your user name: mlh
True
>>> subject = '$$$ Get rich now!!! $$$'
>>> '$$$' in subject
True
However, the only members or elements of a string are its characters. So, the following makes perfect sense:
>>> 'P' in 'Python'
True
Length, Minimum, and Maximum
The built-in functions len, min, and max can be quite useful. The function len returns the number of elements a sequence contains. min and max return the smallest and largest element of the sequence, respectively. (You learn more about comparing objects in Chapter 5, in the section
“Comparison Operators.”)
>>> numbers = [100, 34, 678]
>>> len(numbers)
3
>>> max(numbers)
678
>>> min(numbers)
34
>>> max(2, 3)
3
>>> min(9, 3, 2, 5)
2
How this works should be clear from the previous explanation, except possibly the last two expressions. In those, max and min are not called with a sequence argument; the numbers are supplied directly as arguments.
>>> [42] * 10
[42, 42, 42, 42, 42, 42, 42, 42, 42, 42]
happy coding season..
Note if you are having any difficulty in running my code, simply message me or drop your questions in our social media group.
thanks for visiting.
0 comments:
Post a Comment