UNIT - 2 Python
UNIT - 2 Python
Methods, Lists: Introduction, Accessing list, Operations, Working with lists, Function
and Methods, Tuple: Introduction, Accessing tuples, Operations, Working, Functions
and Methods Dictionaries: Introduction, Accessing values in dictionaries, Working
with dictionaries, Properties.
Lists: Introduction
The most basic data structure in Python is the sequence. Each element of a
sequence is assigned a number - its position or index. The first index is zero, the
second index is one, and so forth.
Python has six built-in types of sequences, but the most common ones are lists
and tuples, which we would see in this tutorial.
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.
Python Lists
The list is a most versatile datatype available in Python which can be written as a
list of comma-separated values (items) between square brackets. Important
thing about a list is that items in a list need not be of the same type.
Creating a list is as simple as putting different comma-
separated values between square brackets. For example −
list1 = ['physics', 'chemistry', 1997, 2000];
list2 = [1, 2, 3, 4, 5 ];
list3 = ["a", "b", "c", "d"]
Similar to string indices, list indices start at 0, and lists can be sliced,
concatenated and so on.
Updating Lists
You can update single or multiple elements of lists by giving the
slice on the left-hand side of the assignment operator, and you can
add to elements in a list with the append() method. For example −
1 cmp(list1, list2)
2 len(list)
3 max(list)
4 min(list)
5 list(seq)
1.cmp()
Description
Python list method cmp() compares elements of two lists.
Syntax
Following is the syntax for cmp() method −
cmp(list1, list2)
Parameters
● list1 − This is the first list to be compared.
● list2 − This is the second list to be compared.
Return Value
If elements are of the same type, perform the compare and return the result. If
elements are different types, check to see if they are numbers.
● If numbers, perform numeric coercion if necessary and compare.
● If either element is a number, then the other element is "larger" (numbers
are "smallest").
● Otherwise, types are sorted alphabetically by name.
If we reached the end of one of the lists, the longer list is "larger." If we exhaust
both lists and share the same data, the result is a tie, meaning that 0 is returned.
Example
The following example shows the usage of cmp() method.
3.max()
Description
Python list method max returns the elements from the list with maximum value.
Syntax
Following is the syntax for max() method −
max(list)
Parameters
● list − This is a list from which max valued element to be
returned.
Return Value
This method returns the elements from the list with maximum value.
Example
The following example shows the usage of max() method.
4.min()
Description
Python list method min() returns the elements from the list with minimum
value.
Syntax
Following is the syntax for min() method −
min(list)
Parameters
● list − This is a list from which min valued element to be
returned.
Return Value
This method returns the elements from the list with minimum value.
Example
The following example shows the usage of min() method.
5.list()
Description
Python list method list() takes sequence types and converts them to lists. This is
used to convert a given tuple into list.
Note − Tuple are very similar to lists with only difference that
element values of a tuple can not be changed and tuple elements
are put between parentheses instead of square bracket.
Syntax
Following is the syntax for list() method −
list( seq )
Parameters
● seq − This is a tuple to be converted into list.
Return Value
This method returns the list.
Example
The following example shows the usage of list() method.
aTuple = (123, 'xyz', 'zara', 'abc');
aList = list(aTuple)
print "List elements : ", aList
When we run above program, it produces following result −
List elements : [123, 'xyz', 'zara', 'abc']
List methods
1 list.append(obj)
Appends object obj to list
2 list.count(obj)
3 list.extend(seq)
4 list.index(obj)
5 list.insert(index, obj)
6 list.pop(obj=list[-1])
7 list.remove(obj)
8 list.reverse()
Reverses objects of list in place
9 list.sort([func])
Tuple: Introduction
A tuple is a collection of objects which ordered and immutable. Tuples are
sequences, just like lists. The differences between tuples and lists are, the tuples
cannot be changed unlike lists and tuples use parentheses, whereas lists use
square brackets.
Creating a tuple is as simple as putting different comma-separated values.
Optionally you can put these comma-separated values between parentheses also.
For example −
tup1 = ('physics', 'chemistry', 1997, 2000);
tup2 = (1, 2, 3, 4, 5 );
tup3 = "a", "b", "c", "d";
Like string indices, tuple indices start at 0, and they can be sliced, concatenated,
and so on.
Accessing Values in Tuples
To access values in tuple, use the square brackets for slicing
along with the index or indices to obtain value available at
that index. For example −
Updating Tuples
Tuples are immutable which means you cannot update or change
the values of tuple elements. You are able to take portions of
existing tuples to create new tuples as the following example
demonstrates −
No Enclosing Delimiters
Any set of multiple objects, comma-separated, written without
identifying symbols, i.e., brackets for lists, parentheses for
tuples, etc., default to tuples, as indicated in these short
examples −
1 cmp(tuple1, tuple2)
2 len(tuple)
3 max(tuple)
4 min(tuple)
Returns item from the tuple with min value.
5 tuple(seq)
Introduction:
Each key is separated from its value by a colon (:), the items are separated by
commas, and the whole thing is enclosed in curly braces. An empty dictionary
without any items is written with just two curly braces, like this: {}.
Keys are unique within a dictionary while values may not be. The values of a
dictionary can be of any type, but the keys must be of an immutable data type
such as strings, numbers, or tuples.
Accessing Values in Dictionary
To access dictionary elements, you can use the familiar square
brackets along with the key to obtain its value. Following is a
simple example −
dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}
print "dict['Name']: ", dict['Name']
print "dict['Age']: ", dict['Age']
When the above code is executed, it produces the following
result −
dict['Name']: Zara
dict['Age']: 7
Updating Dictionary
You can update a dictionary by adding a new entry or a key-
value pair, modifying an existing entry, or deleting an existing
entry as shown below in the simple example −
dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}
dict['Age'] = 8; # update existing entry
dict['School'] = "DPS School"; # Add new entry
(b) Keys must be immutable. Which means you can use strings,
numbers or tuples as dictionary keys but something like ['key']
is not allowed. Following is a simple example −
dict = {['Name']: 'Zara', 'Age': 7}
print "dict['Name']: ", dict['Name']
When the above code is executed, it produces the following
result −
Traceback (most recent call last):
File "test.py", line 3, in <module>
dict = {['Name']: 'Zara', 'Age': 7};
TypeError: unhashable type: 'list'
1 cmp(dict1, dict2)
2 len(dict)
Gives the total length of the dictionary. This would be equal to the
number of items in the dictionary.
3 str(dict)
4 type(variable)
1 dict.clear()
2 dict.copy()
3 dict.fromkeys()
Create a new dictionary with keys from seq and values set to
value.
4 dict.get(key, default=None)
5 dict.has_key(key)
6 dict.items()
7 dict.keys()
8 dict.setdefault(key, default=None)
9 dict.update(dict2)
Adds dictionary dict2's key-values pairs to dict
10 dict.values()