0% found this document useful (0 votes)
7 views17 pages

Revision of Python LIST-TUPLE - DICTIONARY (2) - Amit Yerpude

The document provides a comprehensive overview of Python's data structures: lists, tuples, and dictionaries. It covers their definitions, syntax, operations, and built-in methods, highlighting key features such as mutability in lists, immutability in tuples, and key-value pairs in dictionaries. Additionally, it includes examples and explanations for accessing, modifying, and iterating through these data structures.

Uploaded by

vsubramanian2809
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views17 pages

Revision of Python LIST-TUPLE - DICTIONARY (2) - Amit Yerpude

The document provides a comprehensive overview of Python's data structures: lists, tuples, and dictionaries. It covers their definitions, syntax, operations, and built-in methods, highlighting key features such as mutability in lists, immutability in tuples, and key-value pairs in dictionaries. Additionally, it includes examples and explanations for accessing, modifying, and iterating through these data structures.

Uploaded by

vsubramanian2809
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 17

Revision of Python Part – 2

(List, Tuple, Dictionary)

By:-
Amit Yerpude
PGT(Computer Science)
Kendriya Vidyalaya, Khagaria
Amit Yerpude, PGT CS, 4/9/2020
KV Khagaria

List
• In Python, the list is a collection of items of different
data types.
• It is an ordered sequence of items.
• A list object contains one or more items, not necessarily
of the same type, which are separated by comma and
enclosed in square brackets [].
• Syntax:
list = [value1, value2, value3,...valueN]

• The following declares a list type variable.


>>> names=[“Amit", “Navdeep", “Babulal", “Amir"]
• A list can also contain elements of different types.
>>> orderItem=[101, “Amit", "Computer", 75.50, True]
Amit Yerpude, PGT CS, 4/9/2020
KV Khagaria

An index starts with zero, as shown below.

>>> orderItem=[101, “Amit", "Computer", 75.50, True]


>>> orderItem[0]
101
>>> orderItem[1]
‘Amit'
>>> orderItem[2]
'Computer'
>>> orderItem[3]
75.50
>>> orderItem[4]
True

The list object is mutable. It is possible to modify its contents, which will modify
the value in the memory.

>>> orderItem[2]="Laptop“
>>> orderItem
[101, “Amit", “Laptop", 75.50, True]
List Operators Amit Yerpude, PGT CS,
KV Khagaria
4/9/2020

Operator Description Example


>>> L1=[1,2,3]
Returns a list containing all the elements of the first and the >>> L2=[4,5,6]
+ Concatenation
second list. >>> L1+L2
[1, 2, 3, 4, 5, 6]
>>> L1*4
* Repetition Concatenates multiple copies of the same list.
[1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3]
>>> L1=[1, 2, 3, 4, 5, 6]
>>> L1[3]
Returns the item at the given index. A negative index counts
[] slice 4
the position from the right side.
>>> L1[-2]
5
>>> L1=[1, 2, 3, 4, 5, 6]
Fetches items in the range specified by the two index >>> L1[1:4]
operands separated by : symbol. [2, 3, 4]
[ : ] - Range slice If the first operand is omitted, the range starts from the zero >>> L1[3:]
index. If the second operand is omitted, the range goes up to [4, 5, 6]
the end of the list. >>> L1[:3]
[1, 2, 3]
>>> L1=[1, 2, 3, 4, 5, 6]
>>> 4 in L1
in Returns true if an item exists in the given list. True
>>> 10 in L1
False
>>> L1=[1, 2, 3, 4, 5, 6]
>>> 5 not in L1
not in Returns true if an item does not exist in the given list. False
>>> 10 not in L1
True
Built-in List Methods Amit Yerpude, PGT CS,
KV Khagaria
4/9/2020

len() append()
The len() method returns the number of elements in the Adds an item at the end of the list.
list/tuple. >>> L2=['Python', 'Java', 'C++']
>>> L2.append('PHP')
>>> L1=[12,45,43,8,35]
>>> L2
>>> len(L1)
['Python', 'Java', 'C++', 'PHP']
5
insert()
max() Inserts an item in a list at the specified index.
The max() method returns the largest number, if the list >>> L2=['Python', 'Java', 'C++']
contains numbers. If the list contains strings, the one that >>> L2.insert(1,'Perl')
comes last in alphabetical order will be returned. >>> L2
>>> L1=[12,45,43,8,35] ['Python', 'Perl', 'Java', 'C++‘]
>>> max(L1) remove()
45 Removes a specified object from the list.
>>> L2=['Python', 'Java', 'C++'] >>> L2=['Python', 'Perl', 'Java', 'C++']
>>> max(L2) >>> L2.remove('Java')
'Python' >>> L2
min() ['Python', 'Perl', 'C++']
pop()
The min() method returns the smallest number, if the list Removes and returns the last object in the list.
contains numbers. If the list contains strings, the one that >>> L2=['Python', 'Perl', 'Java', 'C++']
comes first in alphabetical order will be returned. >>> L2.pop()
>>> L1=[12, 45, 43, 8, 35] 'C++'
>>> min(L1) >>> L2
8 ['Python', 'Perl', 'Java']
>>> L2=['Python', 'Java', 'C++'] reverse()
>>> min(L2) Reverses the order of the items in a list.
'C++’ >>> L2=['Python', 'Perl', 'Java', 'C++']
>>> L1=[1,'aa',12.22] >>> L2.reverse()
>>> max(L1) >>> L2
Traceback (most recent call last): ['C++', 'Java', 'Perl', 'Python']
File "<stdin>", line 1, in <module>
TypeError: '>' not supported between instances of 'str'
and 'int'
Built-in List Methods Amit Yerpude, PGT CS,
KV Khagaria
4/9/2020

sort()
Rearranges the items in the list according to the alphabetical order. Default is the ascending order. For
descending order, put reverse=True as an argument in the function bracket.
>>> L2=['Python', 'C++', 'Java', 'Ruby']
>>> L2.sort()
>>> L2
['C++', 'Java', 'Python', 'Ruby']
>>> L2.sort(reverse=True)
>>> L2
['Ruby', 'Python', 'Java', 'C++']

list()

List Function is use to create list and Converts a tuple or string to a list object.
>>> t2=('python', 'java', 'C++')
>>> list(t2)
['python', 'java', 'C++']
>>> s1="Teacher“
>>> list(s1)
['T', 'e', 'a', 'c', 'h', 'e', 'r']

tuple()
Converts a list or string to a tuple object.
>>> L2=['C++', 'Java', 'Python', 'Ruby']
>>> tuple(L2)
('C++', 'Java', 'Python', 'Ruby')
>>> s1="Teacher“
>>> tuple(s1)
('T', 'e', 'a', 'c', 'h', 'e', 'r')
Amit Yerpude, PGT CS, 4/9/2020

Slicing a Python List KV Khagaria

When you want only a part of a Python list, you can use the slicing operator [].

>>> indices=['zero‘,'one‘,'two‘,'three‘,'four‘,'five']
>>> indices[2:4]
[‘two’, ‘three’]
This returns items from index 2 to index 4-1 (i.e., 3)
>>> indices[:4]
[‘zero’, ‘one’, ‘two’, ‘three’]
This returns items from the beginning of the list to index 3.
>>> indices[4:]
[‘four’, ‘five’]
It returns items from index 4 to the end of the list in Python.
>>> indices[:]
[‘zero’, ‘one’, ‘two’, ‘three’, ‘four’, ‘five’]
This returns the whole list.

Negative indices- A negative index means traversal from


the end of the list.
>>> indices[:-2]
[‘zero’, ‘one’, ‘two’, ‘three’]
This returns item from the list’s beginning to two items from the end.
>>> indices[1:-2]
[‘one’, ‘two’, ‘three’]
It returns items from the item at index 1 to two items from the end.
>>> indices[-2:-1]
[‘four’]
Amit Yerpude, PGT CS, 4/9/2020
KV Khagaria

Tuple
•Python Tuples are like a list.
•It can hold a sequence of items.
•The difference is that it is immutable.
•Let’s learn the syntax to create a tuple in Python.
•To declare a Python tuple, you must type a list of
items separated by commas, inside parentheses.
Then assign it to a variable.
>>> percentages=(90,95,89)
Python Tuple Operations
Amit Yerpude, PGT CS, 4/9/2020
KV Khagaria

a. Membership
We can apply the ‘in’ and ‘not in’ operators on items. This tells us whether they belong to the
tuple.
>>> 'a' in tuple("string")
False
>>> 'x' not in tuple("string")
True

b. Concatenation
Like we’ve previously discussed on several occasions, concatenation is the act of joining. We
can join two
tuples using the concatenation operator ‘+’.
>>> (1,2,3)+(4,5,6)
(1, 2, 3, 4, 5, 6)
Other arithmetic operations do not apply on a tuple.

c. Logical
All the logical operators (like >,>=,..) can be applied on a tuple.
>>> (1,2,3)>(4,5,6)
False
>>> (1,2)==('1','2')
False
As is obvious, the ints 1 and aren’t equal to the strings ‘1’ and ‘2’. Likewise, it returns False.
Amit Yerpude, PGT CS, 4/9/2020
KV Khagaria

Python - Dictionary
• Like the list and the tuple, dictionary is also a collection type.
• However, it is not an ordered sequence, and it contains key-value
pairs.
• One or more key:value pairs separated by commas are put inside
curly brackets to form a dictionary object.

• Syntax:
dict = { key1:value1, key2:value2,...keyN:valueN }

• The following declares a dictionary object.


>>> capitals={"USA":"Washington, D.C.", "France":"Paris",
"India":"New Delhi"}

In the above example, capitals is a dictionary object.

• The left side of : is a key and right side of : is a value.


• The key should be An immutable object. A number, string or tuple
can be used as key.
Amit Yerpude, PGT CS, 4/9/2020
KV Khagaria

Accessing a Dictionary
• Dictionary is not an ordered collection, so a value cannot be
accessed using an index in square brackets.
• A value in a dictionary can be fetched using the associated key, using
the get() method.
• Specify the key in the get() method to retrieve its value.

• >>>capitals={"USA":"New York", "France":"Paris",


"Japan":"Tokyo", "India":"New Delhi"}
>>>capitals.get("France")
'Paris'
>>>points={"p1":(10,10), "p2":(20,20)}
>>>points.get("p2")
(20,20)
>>>numbers={1:"one", 2:"Two", 3:"three",4:"four"}
>>>numbers.get(2)
'Two'
Amit Yerpude, PGT CS, 4/9/2020
KV Khagaria

Use the for loop to iterate a dictionary


• capitals={"USA":"Washington, D.C.", "France":"Paris", "Japan":"Tokyo",
"India":"New Delhi"}
for key in capitals:
print("Key = " + key + ", Value = " + capitals[key])

Output:

Key = 'USA', Value = 'Washington, D.C.‘


Key = 'France', Value = 'Paris‘
Key = 'Japan', Value = 'Tokyo‘
Key = 'India', Value = 'New Delhi'
Amit Yerpude, PGT CS, 4/9/2020
KV Khagaria

Deleting Values from a Dictionary

• Use the del keyword to delete a pair from a dictionary or the dictionary
object itself.
• To delete a pair, use its key as parameter.
• To delete a dictionary object, use its name.

>>> captains={'England': 'Root', 'Australia': Paine', 'India': 'Virat', 'Srilanka':


'Jayasurya'}
>>> del captains['Srilanka']
>>> captains
{'England': 'Root', 'Australia': Paine', 'India': 'Virat'}
>>> del captains
>>> captains
NameError: name 'captains' is not defined
Amit Yerpude, PGT CS, 4/9/2020
KV Khagaria

View Keys and Values


• The keys() and values() methods of Python dictionary class return a view object consisting
of keys and values respectively, used in the dictionary.

• >>> d1 = {'name': 'Amit', 'age': 21, 'marks': 60, 'course': 'Computer Engg'}
>>>d1.keys()
dict_keys(['name', 'age', 'marks', 'course'])

• The result of the keys() method is a view which can be stored as a list object. If a new key-
value pair is added, the view object is automatically updated.

• >>> keys=d1.keys()
>>> keys
dict_keys(['name', 'age', 'marks', 'course'])
>>>d1.update({"college":"IITB"})
>>> keys
dict_keys(['name', 'age', 'marks', 'course', 'college'])

• This is similar for the values() method.


• >>> d1= {'name': 'Amit', 'age': 21, 'marks': 60, 'course': 'Computer Engg'}
>>>values=d1.values()
dict_values(['Amit', 21, 60, 'Computer Engg'])
Amit Yerpude, PGT CS, 4/9/2020
KV Khagaria

Multi-dimensional Dictionary

• Let's assume there are three dictionary objects, as below:


• >>> d1={"name":"Amit","age":25, "marks":60}
>>> d2={"name":"Anil","age":23, "marks":75}
>>> d3={"name":"Asha", "age":20, "marks":70}

• Let us assign roll numbers to these students and create a multi-


dimensional dictionary with roll number as key and the above dictionaries
at their value.

• >>> students={1:d1,2:d2,3:d3}
>>> students
{1: {'name': 'Amit', 'age': 25, 'marks': 60}, 2: {'name': 'Anil', 'age': 23,
'marks': 75}, 3: {'name': 'Asha', 'age': 20, 'marks': 70}}
Amit Yerpude, PGT CS, 4/9/2020
KV Khagaria

Method Description
clear() Removes all the elements from the dictionary
copy() Returns a copy of the dictionary
fromkeys() Returns a dictionary with the specified keys and value
get() Returns the value of the specified key
Returns a list containing a tuple for each key value
items()
pair
keys() Returns a list containing the dictionary's keys
pop() Removes the element with the specified key
popitem() Removes the last inserted key-value pair
Returns the value of the specified key. If the key does
setdefault()
not exist: insert the key, with the specified value
Updates the dictionary with the specified key-value
update()
pairs
values() Returns a list of all the values in the dictionary
Amit Yerpude, PGT CS, 4/9/2020
KV Khagaria

Thank you !!!

You might also like