0% found this document useful (0 votes)
28 views19 pages

Py 1

The document provides an overview of data types in Python, focusing on lists, tuples, sets, and dictionaries. It explains how to create, access, modify, and manipulate these data structures, including methods for adding, removing, and sorting items. Additionally, it highlights the characteristics of each data type, such as mutability and ordering.

Uploaded by

Mariya Jacob
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)
28 views19 pages

Py 1

The document provides an overview of data types in Python, focusing on lists, tuples, sets, and dictionaries. It explains how to create, access, modify, and manipulate these data structures, including methods for adding, removing, and sorting items. Additionally, it highlights the characteristics of each data type, such as mutability and ordering.

Uploaded by

Mariya Jacob
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/ 19

Data types and control statement

List
Lists are used to store multiple items in a single variable. Lists are created using square brackets
[]

thislist = ["apple", "banana", "cherry"]


print(thislist)
['apple', 'banana', 'cherry']
List items are

 ordered,
 changeable
 allow duplicate values.

List items are indexed, the first item has index [0], the second item has index [1] etc.

Access Items
thislist = ["apple", "banana", "cherry"]
print(thislist[1])
banana
List = [1, 2, 4, 4, 3, 3, 3, 6, 5]
print(List[1])
2

Negative Indexing

Negative indexing means start from the end

-1 refers to the last item, -2 refers to the second last item etc.
thislist = ["apple", "banana", "cherry"]
print(thislist[-1])
cherry

Range of Indexes

You can specify a range of indexes by specifying where to start and where to end the range.

When specifying a range, the return value will be a new list with the specified items.
list = ["apple", True,1,5,7, "kiwi", "melon", "mango"]
print(list[2:6])
[1, 5, 7, 'kiwi']
By leaving out the start value, the range will start at the first item:
a = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]
print(a[:4])
['apple', 'banana', 'cherry', 'orange']
By leaving out the end value, the range will go on to the end of the list:
a = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]
print(a[2:])
['cherry', 'orange', 'kiwi', 'melon', 'mango']

Change Item Value


a = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]
a[1]=5
print(a)
['apple', 5, 'cherry', 'orange', 'kiwi', 'melon', 'mango']

Change a Range of Item Values


a = ["a", "b", "c"]
a[1:3] = ["e", "t"]
print(a)
['a', 'e', 't']

Add list items


#append() - To add an item to the end of the list

a = ["apple", "banana", "cherry"]


a.append("orange")
print(a)
['apple', 'banana', 'cherry', 'orange']
#insert() - To insert a list item at a specified index

li=['a',1,True,4.0]
li.insert(1, "python")
print(li)
['a', 'python', 1, True, 4.0]
#extend() - To append elements from another list to the current list

li=['a',1,True,4.0]
b = ["apple", "banana", "cherry"]
li.extend(b)
print(li)
['a', 1, True, 4.0, 'apple', 'banana', 'cherry']
#The extend() method does not have to append lists, you can add any iterable object (tuples, sets, dictionaries et
c.).

li=['a',1,True,4.0]
b = ("hello",5)
li.extend(b)
print(li)

['a', 1, True, 4.0, 'hello', 5]

Remove List Items


#remove() method removes the specified item.
a=['a', 1, True, 4.0, 'hello', 5]
a.remove("hello")
print(a)
['a', 1, True, 4.0, 5]
#pop() method removes the specified index.

x=['a', 1, True, 4.0, 'hello', 5]


x.pop()
x

Out[26]:
['a', 1, True, 4.0, 'hello']
# del keyword also removes the specified index:

y=['a', 1, True, 4.0, 'hello', 5]


del y[0]
print(y)
[1, True, 4.0, 'hello', 5]
#del keyword can also delete the list completely.

z=[6, 3, 9, 10]
del z

Loop Lists
y=['a', 1, True, 4.0, 'hello', 5]
for x in y:
print(x)
a
1
True
4.0
hello
5
thislist = ["apple", "banana", "cherry"]
for i in range(len(thislist)):
print(thislist[i])
apple
banana
cherry
#shorthand if

a = ["apple", "banana", "cherry"]


[print(x) for x in a]
apple
banana
cherry
Out[34]:
[None, None, None]
a = ["apple", "banana", "cherry"]
i=0
while i < len(a):
print(a[i])
i=i+1
apple
banana
cherry

Sort List
#sort() method that will sort the list alphanumerically, ascending, by default:

thislist = ["orange", "mango", "kiwi", "pineapple", "banana"]


thislist.sort()
print(thislist)
['banana', 'kiwi', 'mango', 'orange', 'pineapple']
thislist = [100, 50, 65, 82, 23]
thislist.sort()
print(thislist)
[23, 50, 65, 82, 100]
x=['a', 1, True, 4.0, 'hello', 5]
x.sort()
x
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-1-bdc2e1c03caa> in <module>()
1 x=['a', 1, True, 4.0, 'hello', 5]
----> 2 x.sort()
3 x

TypeError: '<' not supported between instances of 'int' and 'str'

#To sort descending, use the keyword argument reverse = True:


thislist = ["orange", "mango", "kiwi", "pineapple", "banana"]
thislist.sort(reverse = True)
print(thislist)
['pineapple', 'orange', 'mango', 'kiwi', 'banana']
thislist = [10, 50, 65, 82, 23]
thislist.sort(reverse = True)
print(thislist)
[82, 65, 50, 23, 10]
Copy a List
a = ["apple", "banana", "cherry"]
mylist = a.copy()
print(mylist)
['apple', 'banana', 'cherry']

Join Lists
list1 = ["a", "b", "c"]
list2 = [1, 2, 3]

list3 = list1 + list2


print(list3)
['a', 'b', 'c', 1, 2, 3]
list1 = ["a", "b" , "c"]
list2 = [1, 2, 3]

list1.extend(list2)
print(list1)
['a', 'b', 'c', 1, 2, 3]
list1 = ["a", "b" , "c"]
list2 = [1, 2, 3]

list1.append(list2)
print(list1)
['a', 'b', 'c', [1, 2, 3]]
list1 = ["a", "b" , "c"]
list2 = [1, 2, 3]

for x in list2:
list1.append(x)

print(list1)
['a', 'b', 'c', 1, 2, 3]

List methods
#count() Returns the number of elements with the specified value

fruits = ['apple', 'banana', 'cherry']

x = fruits.count("cherry")
x
Out[3]:
1
points = [1, 4, 2, 9, 7, 8, 9, 3, 1]

x = points.count(9)
x
Out[2]:
2
#index() method returns the position at the first occurrence of the specified value.

fruits = ['apple', 'banana', 'cherry']

x = fruits.index("cherry")
x
Out[4]:
2
fruits = [4, 55, 64, 32, 16, 32]

x = fruits.index(32)
x
Out[5]:
3
#reverse() method reverses the sorting order of the elements.

fruits = ['apple', 'banana', 'cherry']

fruits.reverse()
fruits
Out[6]:
['cherry', 'banana', 'apple']
fruits = [4, 55, 64, 32, 16, 32]

fruits.reverse()
fruits
Out[9]:
[32, 16, 32, 64, 55, 4]

Tuple
Tuples are used to store multiple items in a single variable. Tuples are created using round
brackets ( )

Tuple items are

 ordered,
 unchangeable
 allow duplicate values.

t=('a','b','c','c')
t
Out[10]:
('a', 'b', 'c', 'c')
Tuple Length

len() function: determine how many items a tuple has


t=('a','b','c','c')
len(t)
Out[11]:
4
To create a tuple with only one item, you have to add a comma after the item, otherwise Python
will not recognize it as a tuple.
a = ("apple",)
print(type(a))

#NOT a tuple
b = ("apple")
print(type(b))
<class 'tuple'>
<class 'str'>
mytuple = ("apple", "banana", "cherry")
print(type(mytuple))
<class 'tuple'>

Access Tuple Items


mytuple = ("apple", "banana", "cherry")
print(mytuple[1])

Banana

Negative Indexing
mytuple = ("apple", "banana", "cherry")
print(mytuple[-1])
cherry

Range of Indexes
mytuple = ("apple", "banana", "cherry",True, False, False,5, 7, 9,)
print(mytuple[1:3])
('banana', 'cherry')
mytuple = ("apple", "banana", "cherry",True, False, False,5, 7, 9,)
print(mytuple[5:])
(False, 5, 7, 9)
mytuple = ("apple", "banana", "cherry",True, False, False,5, 7, 9,)
print(mytuple[:5])
('apple', 'banana', 'cherry', True, False)
mytuple = ("apple", "banana", "cherry",True, False, False,5, 7, 9,)
print(mytuple[-4:-1])
(False, 5, 7)

unchangeable

Once a tuple is created, you cannot change its values. Tuples are unchangeable, or immutable
as it also is called.
Loop Tuples
thistuple = ("apple", "banana", "cherry")
for x in thistuple:
print(x)
apple
banana
cherry
thistuple = ("apple", "banana", "cherry")
for i in range(len(thistuple)):
print(thistuple[i])
apple
banana
cherry
mytuple = ("apple", "banana", "cherry",True, False, False,5, 7, 9,)
i=0
while i < len(mytuple):
print(mytuple[i])
i=i+1
apple
banana
cherry
True
False
False
5
7
9

Join Tuples
tuple1 = ("a", "b" , "c")
tuple2 = (1, 2, 3)

tuple3 = tuple1 + tuple2


print(tuple3)
('a', 'b', 'c', 1, 2, 3)

Tuple Methods
#count() Returns the number of times a specified value occurs in a tuple

thistuple = (1, 3, 7, 8, 7, 5, 4, 6, 8, 5)

x = thistuple.count(5)

print(x)
2
#index() - Searches the tuple for a specified value and returns the position of where it was found

thistuple = (1, 3, 7, 8, 7, 5, 4, 6, 8, 5)

x = thistuple.index(8)

print(x)
3

Sets
A set is a collection which is

 unordered
 unchangeable*
 unindexed
 Duplicates Not Allowed
sets are created using round brackets { }
thisset = {"apple", "banana", "cherry", "apple"}

print(thisset)
{'cherry', 'apple', 'banana'}

Access Set Items


thisset = {"apple", "banana", "cherry"}

for x in thisset:
print(x)
cherry
apple
banana

Add Set Items


#add() to add one item to a set

thisset = {"apple", "banana", "cherry"}


thisset.add("orange")
print(thisset)
{'cherry', 'apple', 'orange', 'banana'}

Add Sets
#update() To add items from another set into the current set

thisset = {"apple", "banana", "cherry"}


tropical = {"pineapple", "mango", "papaya"}

thisset.update(tropical)

print(thisset)
{'mango', 'papaya', 'pineapple', 'apple', 'banana', 'cherry'}

Remove Item
#remove() - to remove an item in a set

thisset = {"apple", "banana", "cherry"}


thisset.remove("banana")
print(thisset)
{'cherry', 'apple'}
#discard() - remove item

thisset = {"apple", "banana", "cherry"}


thisset.discard("banana")
print(thisset)
{'cherry', 'apple'}
If the item to remove does not exist, discard() will NOT raise an error.
#pop remove the last item

thisset = {"apple", "banana", "cherry"}

x = thisset.pop()
print(x)
print(thisset)

cherry
{'apple', 'banana'}
#del keyword will delete the set completely:

thisset = {"apple", "banana", "cherry"}

del thisset

print(thisset)
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-43-1a248155c079> in <module>()
5 del thisset
6
----> 7 print(thisset)

NameError: name 'thisset' is not defined

Loop Items
thisset = {"apple", "banana", "cherry"}

for x in thisset:
print(x)
cherry
apple
banana

Join Sets
#union() method returns a new set with all items from both sets:

set1 = {"a", "b" , "c"}


set2 = {1, 2, 3}

set3 = set1.union(set2)
print(set3)
{'c', 1, 2, 3, 'a', 'b'}
#update() method inserts the items in set2 into set1:
set1 = {"a", "b" , "c"}
set2 = {1, 2, 3}

set1.update(set2)
print(set1)
{'c', 1, 2, 3, 'a', 'b'}
Both union() and update() will exclude any duplicate items.
#intersection_update() method will keep only the items that are present in both sets.

x = {"apple", "banana", "cherry"}


y = {"google", "microsoft", "apple"}

x.intersection_update(y)

print(x)

{'apple'}

Dictionary
key:value pairs

A dictionary is a collection which

 ordered
 changeable
 do not allow duplicates

thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
"year": 2000
}
print(thisdict)
{'brand': 'Ford', 'model': 'Mustang', 'year': 1964}
#len
print(len(thisdict))
3
#type()
print(type(thisdict))
<class 'dict'>

Accessing Items
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = thisdict["model"]
x
Out[54]:
'Mustang'
#get()
y = thisdict.get("year")
y
Out[57]:
1964
#keys() method will return a list of all the keys in the dictionary.

thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = thisdict.keys()
x
Out[59]:
dict_keys(['brand', 'model', 'year'])
#values() method will return a list of all the values in the dictionary.

thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = thisdict.values()
x
Out[60]:
dict_values(['Ford', 'Mustang', 1964])
#items() method will return each item in a dictionary, as tuples in a list.

thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = thisdict.items()
x
Out[61]:
dict_items([('brand', 'Ford'), ('model', 'Mustang'), ('year', 1964)])

Change Values
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict["year"] = 2018

thisdict
Out[62]:
{'brand': 'Ford', 'model': 'Mustang', 'year': 2018}
#update() method will update the dictionary with the items from the given argument.
#The argument must be key:value pairs.

thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict.update({"year": 2020})
thisdict
Out[63]:
{'brand': 'Ford', 'model': 'Mustang', 'year': 2020}

Adding Items
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict["color"] = "red"
print(thisdict)
{'brand': 'Ford', 'model': 'Mustang', 'year': 1964, 'color': 'red'}
#update() method:

thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict.update({"color": "red"})
thisdict
Out[66]:
{'brand': 'Ford', 'model': 'Mustang', 'year': 1964, 'color': 'red'}

Removing Items
#pop() method removes the item with the specified key name:

thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict.pop("model")
print(thisdict)
{'brand': 'Ford', 'year': 1964}
#popitem() method removes the last inserted item

thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict.popitem()
print(thisdict)
{'brand': 'Ford', 'model': 'Mustang'}
#del keyword removes the item with the specified key name:

thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
del thisdict["model"]
print(thisdict)
{'brand': 'Ford', 'year': 1964}

Loop Dictionaries
Employee = {
"Name": "John",
"Age": 29,
"salary":25000,
"Company":"GOOGLE"
}

for x in Employee: #Print all key names in the dictionary


print(x)
Name
Age
salary
Company
#keys() method to return the keys of a dictionary:

for x in Employee.keys():
print(x)
Name
Age
salary
Company
#Print all values in the dictionary
for x in Employee:
print(Employee[x])
John
29
25000
GOOGLE
#values() method to return values of a dictionary:

for x in Employee.values():
print(x)
John
29
25000
GOOGLE
#items() method: Loop through both keys and values

for x, y in Employee.items():
print(x, y)
Name John
Age 29
salary 25000
Company GOOGLE

Copy a Dictionary
#copy() method:

Employee = {
"Name": "John",
"Age": 29,
"salary":25000,
"Company":"GOOGLE"
}

mydict = Employee.copy()
print(mydict)
{'Name': 'John', 'Age': 29, 'salary': 25000, 'Company': 'GOOGLE'}
#dict() Make a copy of a dictionary

mydict = dict(Employee)
print(mydict)
{'Name': 'John', 'Age': 29, 'salary': 25000, 'Company': 'GOOGLE'}

Nested Dictionaries
# Nested dictionary having same keys
Dict = { 'Dict1': {'name': 'Ali', 'age': '19'},
'Dict2': {'name': 'Bob', 'age': '25'}}
print("\nNested dictionary -")
print(Dict)

Nested dictionary -
{'Dict1': {'name': 'Ali', 'age': '19'}, 'Dict2': {'name': 'Bob', 'age': '25
'}}
# Nested dictionary of mixed dictionary keys
Dict = { 'Dict1': {1: 'G', 2: 'F', 3: 'G'},
'Dict2': {'Name': 'Ali', 1: [1, 2]} }
print("\nNested dictionary -")
print(Dict)

Conditions statements
if statments.
Python supports the usual logical conditions

 Equals: a == b
 Not Equals: a != b
 Less than: a < b
 Less than or equal to: a <= b
 Greater than: a > b
 Greater than or equal to: a >= b

x=30;y=40;z=30
if x<y:
print("y is greater")
y is greater

if...else statements
if y<z:
print("y is greater")
else:
print("z is greater")
z is greater

Elif

The elif keyword is pythons way of saying "if the previous conditions were not true, then try this
condition".
if x>y:
print("x is greater")
elif y>x:
print("y is greater")
else:
print("x and y are equal")
y is greater

Nested If

You can have if statements inside if statements, this is called nested if statements.
if x>=y:
if x>=z:
print(x,"is greater")
else:
print(z,"is greater")
else:
if y>z:
print(y," is greater")
else:
print(z,"is greater")
40 is greater

And / or

The and / or keyword is a logical operator, and is used to combine conditional statements:
a = 200
b = 33
c = 500
if a > b and c > a:
print("Both conditions are True")
Both conditions are True
a = 200
b = 33
c = 500
if a > b or a > c:
print("At least one of the conditions is True")
At least one of the conditions is True
if x>y and x>z:
print("x is greater")
elif y>x and y>z:
print("y is greater")
elif z>x and z>y:
print("z is greater")
elif x==y:
if x==z:
print("x, y and z are equal")
else:
print("x and y are equal")
elif y==z:
print("y and z are equal")
else:
print("x and z are equal")
y is greater
Short Hand If

If you have only one statement to execute, you can put it on the same line as the if statement.
a = 200
b = 33
if a > b: print("a is greater than b")
a is greater than b
Short Hand If ... Else
If you have only one statement to execute, one for if, and one for else, you can put it all on the
same line:
a=2
b = 330

print("A") if a > b else print("B")


B
#You can also have multiple else statements on the same line:

x=2
y = 330
print(x) if x > y else print(y) if x==y else print(y)
330
pass Statement

if statements cannot be empty, but if you for some reason have an if statement with no content,
put in the pass statement to avoid getting an error.
a = 33
b = 200

if b > a:
pass

Iterators
An iterator is an object that contains a countable number of values.
an iterator is an object which implements the iterator protocol, which consist of the methods iter()
and next().
mylist = [2,4,6,8]
list = iter(mylist)

print(next(list))
print(next(list))
print(next(list))
print(next(list))
2
4
6
8
mytuple = ("apple", "banana", "cherry")
mytup = iter(mytuple)

print(next(mytup))
apple

Exercise To Practise

LIST

1.Python program to swap two elements in a list


2.Reverse a List

3.Python program to find smallest number in a list

4.Python program to find largest number in a list

5.Python program to count Even and Odd numbers in a List

TUPLE

1. Write a Python program to create a tuple with different data types.


2. Write a Python program to add an item in a tuple.
3. Write a Python program to find the repeated items of a tuple.
4. Write a Python program to check whether an element exists within a tuple.
5. Write a Python program to remove an item from a tuple.

SET

1.write a python program to remove an item from a set if it is present in the set.

2.write a python program to create an intersection of sets.

3.write a python program to create a union of sets

4.wrie a python program to check if a set is a subset of another set.

5.write a python program to find maximum and the minimum value in a set.

DICTIONARY

1.write a python script to add a key to a dictionary.

sample={0:10,1:20}

expected output={0:10,1:20,2:30}

2.write a python script to concatenate following dictionaries to create a new one.

sample dictionary:

dic1={1:10,2:20}

dic2={3:30,4:40}

dic3={5:50,6:60}

expected result:{1:10,2:20,3:30,4:40,5:50,6:60}

3.write a python program to check whether a given key already exists in a dictionary.

4.write a python program to sum all the items in a dictionary.

5.write a python program to sort a dictionary by key.

You might also like