0% found this document useful (0 votes)
5 views

UNIT - 2 Python

Uploaded by

Hansika Erroju
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

UNIT - 2 Python

Uploaded by

Hansika Erroju
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 22

UNIT – II:

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.

Accessing Values in Lists


To access values in lists, use the square brackets for slicing along
with the index or indices to obtain value available at that index. For
example −
#!/usr/bin/python

list1 = ['physics', 'chemistry', 1997, 2000];


list2 = [1, 2, 3, 4, 5, 6, 7 ];
print "list1[0]: ", list1[0]
print "list2[1:5]: ", list2[1:5]
When the above code is executed, it produces the following result −
list1[0]: physics
list2[1:5]: [2, 3, 4, 5]

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 −

list = ['physics', 'chemistry', 1997, 2000];


print "Value available at index 2 : "
print list[2]
list[2] = 2001;
print "New value available at index 2 : "
print list[2]
Note − append() method is discussed in the subsequent section.
When the above code is executed, it produces the following result −
Value available at index 2 :
1997
New value available at index 2 :
2001

Delete List Elements


To remove a list element, you can use either the del statement if you
know exactly which element(s) you are deleting or the remove()
method if you do not know. For example −

list1 = ['physics', 'chemistry', 1997, 2000];


print list1
del list1[2];
print "After deleting value at index 2 : "
print list1
When the above code is executed, it produces following result −
['physics', 'chemistry', 1997, 2000]
After deleting value at index 2 :
['physics', 'chemistry', 2000]

Note − remove() method is discussed in the subsequent section.

Basic List Operations


Lists respond to the + and * operators much like strings; they mean concatenation and
repetition here too, except that the result is a new list, not a string.
In fact, lists respond to all of the general sequence operations we used on strings in the
prior chapter.

Python Expression Results Description

len([1, 2, 3]) 3 Length

[1, 2, 3] + [4, 5, 6] [1, 2, 3, 4, 5, 6] Concatenation

['Hi!'] * 4 ['Hi!', 'Hi!', 'Hi!', 'Hi!'] Repetition

3 in [1, 2, 3] True Membership

for x in [1, 2, 3]: print x, 123 Iteration


Indexing, Slicing, and Matrixes
Because lists are sequences, indexing and slicing work the same way for lists as they do
for strings.
Assuming following input −
L = ['spam', 'Spam', 'SPAM!']

Python Expression Results Description

L[2] SPAM! Offsets start at zero

L[-2] Spam Negative: count from the


right

L[1:] ['Spam', 'SPAM!'] Slicing fetches sections

Built-in List Functions & Methods


Python includes the following list functions −
Sr.N Function with Description
o.

1 cmp(list1, list2)

Compares elements of both lists.

2 len(list)

Gives the total length of the list.

3 max(list)

Returns item from the list with max value.

4 min(list)

Returns item from the list with min value.

5 list(seq)

Converts a tuple into list.

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.

list1, list2 = [123, 'xyz'], [456, 'abc']


print cmp(list1, list2)
print cmp(list2, list1)
list3 = list2 + [786];
print cmp(list2, list3)
When we run above program, it produces following result −
-1
1
-1
6
2.len()
Description
Python list method len() returns the number of elements in the list.
Syntax
Following is the syntax for len() method −
len(list)
Parameters
● list − This is a list for which number of elements to be
counted.
Return Value
This method returns the number of elements in the list.
Example
The following example shows the usage of len() method.

list1, list2 = [123, 'xyz', 'zara'], [456, 'abc']


print "First list length : ", len(list1)
print "Second list length : ", len(list2)
When we run above program, it produces following result −
First list length : 3
Second list length : 2

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.

list1, list2 = [123, 'xyz', 'zara', 'abc'], [456, 700, 200]


print "Max value element : ", max(list1)
print "Max value element : ", max(list2)
When we run above program, it produces following result −
Max value element : zara
Max value element : 700

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.

list1, list2 = [123, 'xyz', 'zara', 'abc'], [456, 700, 200]


print "min value element : ", min(list1)
print "min value element : ", min(list2)
When we run above program, it produces following result −
min value element : 123
min value element : 200

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

Python includes following list methods

Sr.N Methods with Description


o.

1 list.append(obj)
Appends object obj to list

2 list.count(obj)

Returns count of how many times obj occurs in list

3 list.extend(seq)

Appends the contents of seq to list

4 list.index(obj)

Returns the lowest index in list that obj appears

5 list.insert(index, obj)

Inserts object obj into list at offset index

6 list.pop(obj=list[-1])

Removes and returns last object or obj from list

7 list.remove(obj)

Removes object obj from list

8 list.reverse()
Reverses objects of list in place

9 list.sort([func])

Sorts objects of list, use compare func if given

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";

The empty tuple is written as two parentheses containing


nothing −
tup1 = ();
To write a tuple containing a single value you have to include a
comma, even though there is only one value −
tup1 = (50,);

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 −

tup1 = ('physics', 'chemistry', 1997, 2000);


tup2 = (1, 2, 3, 4, 5, 6, 7 );
print "tup1[0]: ", tup1[0];
print "tup2[1:5]: ", tup2[1:5];
When the above code is executed, it produces the following
result −
tup1[0]: physics
tup2[1:5]: [2, 3, 4, 5]

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 −

tup1 = (12, 34.56);


tup2 = ('abc', 'xyz');

# Following action is not valid for tuples


# tup1[0] = 100;

# So let's create a new tuple as follows


tup3 = tup1 + tup2;
print tup3;
When the above code is executed, it produces the following
result −
(12, 34.56, 'abc', 'xyz')

Delete Tuple Elements


Removing individual tuple elements is not possible. There is, of course, nothing
wrong with putting together another tuple with the undesired elements
discarded.
To explicitly remove an entire tuple, just use the del
statement. For example −

tup = ('physics', 'chemistry', 1997, 2000);


print tup;
del tup;
print "After deleting tup : ";
print tup;
This produces the following result. Note an exception raised,
this is because after del tup tuple does not exist any more −
('physics', 'chemistry', 1997, 2000)
After deleting tup :
Traceback (most recent call last):
File "test.py", line 9, in <module>
print tup;
NameError: name 'tup' is not defined

Basic Tuples Operations


Tuples respond to the + and * operators much like strings; they mean
concatenation and repetition here too, except that the result is a new tuple, not a
string.
In fact, tuples respond to all of the general sequence
operations we used on strings in the prior chapter −

Python Expression Results Description

len((1, 2, 3)) 3 Length


(1, 2, 3) + (4, 5, 6) (1, 2, 3, 4, 5, 6) Concatenation

('Hi!',) * 4 ('Hi!', 'Hi!', 'Hi!', 'Hi!') Repetition

3 in (1, 2, 3) True Membership

for x in (1, 2, 3): print x, 123 Iteration

Indexing, Slicing, and Matrixes


Because tuples are sequences, indexing and slicing work the
same way for tuples as they do for strings. Assuming following
input −
L = ('spam', 'Spam', 'SPAM!')

Python Expression Results Description

L[2] 'SPAM!' Offsets start at zero

L[-2] 'Spam' Negative: count from


the right

L[1:] ['Spam', 'SPAM!'] Slicing fetches sections

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 −

print 'abc', -4.24e93, 18+6.6j, 'xyz';


x, y = 1, 2;
print "Value of x , y : ", x,y;
When the above code is executed, it produces the following
result −
abc -4.24e+93 (18+6.6j) xyz
Value of x , y : 1 2

Built-in Tuple Functions


Python includes the following tuple functions −

Sr.N Function with Description


o.

1 cmp(tuple1, tuple2)

Compares elements of both tuples.

2 len(tuple)

Gives the total length of the tuple.

3 max(tuple)

Returns item from the tuple with max value.

4 min(tuple)
Returns item from the tuple with min value.

5 tuple(seq)

Converts a list into tuple.

Dictionaries: Introduction, Accessing values in dictionaries, Working with


dictionaries, Properties.

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

If we attempt to access a data item with a key, which is not part


of the dictionary, we get an error as follows −

dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}


print "dict['Alice']: ", dict['Alice']
When the above code is executed, it produces the following
result −
dict['Alice']:
Traceback (most recent call last):
File "test.py", line 4, in <module>
print "dict['Alice']: ", dict['Alice'];
KeyError: 'Alice'

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

print "dict['Age']: ", dict['Age']


print "dict['School']: ", dict['School']
When the above code is executed, it produces the following
result −
dict['Age']: 8
dict['School']: DPS School

Delete Dictionary Elements


You can either remove individual dictionary elements or clear the entire contents
of a dictionary. You can also delete an entire dictionary in a single operation.
To explicitly remove an entire dictionary, just use the del
statement. Following is a simple example −

dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}


del dict['Name']; # remove entry with key 'Name'
dict.clear(); # remove all entries in dict
del dict ; # delete entire dictionary

print "dict['Age']: ", dict['Age']


print "dict['School']: ", dict['School']
This produces the following result. Note that an exception is
raised because after del dict dictionary does not exist any
more −
dict['Age']:
Traceback (most recent call last):
File "test.py", line 8, in <module>
print "dict['Age']: ", dict['Age'];
TypeError: 'type' object is unsubscriptable

Note − del() method is discussed in the subsequent section.


Properties of Dictionary Keys
Dictionary values have no restrictions. They can be any arbitrary Python object,
either standard objects or user-defined objects. However, the same is not true for
the keys.
There are two important points to remember about dictionary
keys −
(a) More than one entry per key not allowed. Which means no
duplicate key is allowed. When duplicate keys are encountered
during assignment, the last assignment wins. For example −

dict = {'Name': 'Zara', 'Age': 7, 'Name': 'Manni'}


print "dict['Name']: ", dict['Name']
When the above code is executed, it produces the following
result −
dict['Name']: Manni

(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'

Built-in Dictionary Functions & Methods


Python includes the following dictionary functions −

Sr.N Function with Description


o.

1 cmp(dict1, dict2)

Compares elements of both dict.

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)

Produces a printable string representation of a dictionary

4 type(variable)

Returns the type of the passed variable. If passed variable is


dictionary, then it would return a dictionary type.

Python includes following dictionary methods −

Sr.N Methods with Description


o.

1 dict.clear()

Removes all elements of dictionary dict

2 dict.copy()

Returns a shallow copy of dictionary dict

3 dict.fromkeys()
Create a new dictionary with keys from seq and values set to
value.

4 dict.get(key, default=None)

For key key, returns value or default if key not in dictionary

5 dict.has_key(key)

Returns true if key in dictionary dict, false otherwise

6 dict.items()

Returns a list of dict's (key, value) tuple pairs

7 dict.keys()

Returns list of dictionary dict's keys

8 dict.setdefault(key, default=None)

Similar to get(), but will set dict[key]=default if key is not already


in dict

9 dict.update(dict2)
Adds dictionary dict2's key-values pairs to dict

10 dict.values()

Returns list of dictionary dict's values

PRACTISE EXAMPLE PROGRAMS

You might also like