Py 1
Py 1
List
Lists are used to store multiple items in a single variable. Lists are created using square brackets
[]
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
-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']
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)
Out[26]:
['a', 1, True, 4.0, 'hello']
# del keyword also removes the specified index:
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
Sort List
#sort() method that will sort the list alphanumerically, ascending, by default:
Join Lists
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
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.
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.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 ( )
ordered,
unchangeable
allow duplicate values.
t=('a','b','c','c')
t
Out[10]:
('a', 'b', 'c', 'c')
Tuple Length
#NOT a tuple
b = ("apple")
print(type(b))
<class 'tuple'>
<class 'str'>
mytuple = ("apple", "banana", "cherry")
print(type(mytuple))
<class 'tuple'>
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)
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'}
for x in thisset:
print(x)
cherry
apple
banana
Add Sets
#update() To add items from another set into the current set
thisset.update(tropical)
print(thisset)
{'mango', 'papaya', 'pineapple', 'apple', 'banana', 'cherry'}
Remove Item
#remove() - to remove an item in a set
x = thisset.pop()
print(x)
print(thisset)
cherry
{'apple', 'banana'}
#del keyword will delete the set completely:
del thisset
print(thisset)
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-43-1a248155c079> in <module>()
5 del thisset
6
----> 7 print(thisset)
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:
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.intersection_update(y)
print(x)
{'apple'}
Dictionary
key:value pairs
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.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
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
TUPLE
SET
1.write a python program to remove an item from a set if it is present in the set.
5.write a python program to find maximum and the minimum value in a set.
DICTIONARY
sample={0:10,1:20}
expected output={0:10,1:20,2:30}
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.