List, Tupels&dictionary
List, Tupels&dictionary
List, Tupels&dictionary
Strings are amongst the most popular types in Python. We can create them simply by
enclosing characters in quotes.
Python treats single quotes the same as double quotes.
Creating strings is as simple as assigning a value to a variable.
For example:
var1 = 'Hello World!'
var2 = "Python Programming"
ssg 1
PYTHON STRINGS
• Python does not support a character type; these are treated as strings of length one, thus also
considered a substring.
• To access substrings, use the square brackets for slicing along with the index or indices to obtain
your substring:
• Example:
var 1 = 'Hello World!'
var2 = "Python Programming"
print "var1[0]: ", var1[0]
print "var2[1:5]: ", var2[1:5]
ssg 2
PYTHON STRINGS
• You can "update" an existing string by (re)assigning a variable to
another string. The new value can be related to its previous value or
to a completely different string altogether.
• Example:
var1 = 'Hello World!'
print "Updated String :- ", var1[:6] + 'Python'
ssg 4
PYTHON STRINGS
ssg 5
PYTHON STRINGS
ssg 6
PYTHON STRINGS
• Python's triple quotes comes to the rescue by allowing strings to span
multiple lines, including verbatim NEWLINEs, TABs, and any other special
characters.
• The syntax for triple quotes consists of three consecutive single or double
quotes.
para_str = """this is a long string that is made up
of several lines and non-printable characters such
as TAB ( \t ) and they will show up that way when
displayed. NEWLINEs within the string, whether
explicitly given like this within the brackets [ \n
], or just a NEWLINE within the variable assignment
will also show up. """
print para_str;
ssg 7
PYTHON STRINGS
• Raw strings don't treat the backslash as a special character at all. Every
character you put into a raw string stays the way you wrote it:
print 'C:\\nowhere'
This would print following result:
C:\nowhere
Now let's make use of raw string. We would put expression in r'expression'
as follows:
print r'C:\\nowhere'
This would print following result:
C:\\nowhere
ssg 8
PYTHON STRINGS
• Normal strings in Python are stored internally as 8-bit ASCII, while
Unicode strings are stored as 16-bit Unicode. This allows for a more
varied set of characters, including special characters from most
languages in the world. I'll restrict my treatment of Unicode strings to
the following:
print u'Hello, world!'
This would print following result:
Hello, world!
ssg 9
PYTHON STRINGS
• To access a range of characters in the String, the method of slicing is
used.
• Slicing in a String is done by using a Slicing operator (colon).
ssg 10
PYTHON STRINGS
• # Creating a String
• String1 = "hello Students"
• print("Initial String: ")
• print(String1)
•
• # Printing 3rd to 12th character
• print("\nSlicing characters from 3-12: ")
• print(String1[3:12])
•
• # Printing characters between
• # 3rd and 2nd last character
• print("\nSlicing characters between " +
• "3rd and 2nd last character: ")
• print(String1[3:-1])
ssg 11
PYTHON STRINGS
ssg 12
PYTHON STRINGS
ssg 13
PYTHON STRINGS
ssg 14
PYTHON STRINGS
ssg 15
How to change or delete a string?
• my_string=‘students’
• my_string=‘Python’
ssg 16
How to change or delete a string?
del my_string
ssg 17
String Operation
• Concatenation of Two or More Strings
Joining of two or more strings into a single one is called
concatenation.
The + operator does this in Python. Simply writing two string literals
together also concatenates them.
•
The * operator can be used to repeat the string for a given number of
times.
ssg 18
String Operation
• Str1=‘Hello’
• Str2=‘world’
• print(str1+str2)
• print(str1*3)
ssg 19
Iterating Through a string
ssg 20
Python Strings
• There are two membership logical operators in Python which are
(in) & (not in). They are used to check whether the given element is
a part of the given string or not.
ssg 21
Python Strings
str1="hello students"
str2="hello"
print('str2 is a part of str1:',str2 in str1)
ssg 22
PYTHON LISTS
• Lists are used to store multiple items in a single variable.
• Lists are one of 4 built-in data types in Python used to store
collections of data, the other 3 are Tuple, Set, and Dictionary, all with
different qualities and usage.
• Lists are created using square brackets:
• Create a list
• List1 = ["apple", "banana", "cherry"]
print(List1)
ssg 23
PYTHON LISTS
List Items - Data Types
ssg 24
PYTHON LISTS
• A list with strings, integers and boolean values:
• list1 = ["abc", 34, True, 40, "male"]
type()
From Python's perspective, lists are defined as objects with the data
type 'list':
It is also possible to use the list() constructor when creating a new list.
ssg 25
PYTHON LISTS
Access Items
• List items are indexed and you can access them by referring to the index
number:
thislist = ["apple", "banana", "cherry"]
print (thislist[1])
The first item has index 0
Negative Indexing
Negative indexing means start from the end
-1 refers to the last item, -2 refers to the second last item etc.
ssg 26
PYTHON LISTS
• 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.
thislist =
["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]
print(thislist[2:5])
ssg 27
PYTHON LISTS
• thislist = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]
print(thislist[2:])
• Range of Negative Indexes
• Specify negative indexes if you want to start the search from the end of the
list:
thislist = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]
print(thislist[-4:-1])
ssg 28
PYTHON LISTS
• List slicing:
list=[3,5,7,9,11]
print(list[0:5])
print(list[-1])
print(list[-2])
Swap…..
list[0],list[-1]=list[-1],list[-0]
print(list)
ssg 29
PYTHON LISTS
Given a list, write a Python program to swap first and last element of the list.
list=[3,5,7,9]
print(list)
#swap the first element with the last element
n=len(list)
temp=list[0]
list[0]=list[n-1]
list[n-1]=temp
print(list)
ssg 30
PYTHON LISTS
• Using * operand.
This operand proposes a change to iterable unpacking syntax,
allowing to specify a “catch-all” name which will be assigned a list of
all items not assigned to a “regular” name.
list=[3,5,7,9]
a,b,*c=list
print(a)
print(b)
print(c)
ssg 31
PYTHON LISTS
Check if Item Exists
To determine if a specified item is present in a list use
the in keyword:
ssg 32
PYTHON LISTS
• Change Item Value
To change the value of a specific item, refer to the index number:
Example
Change the second item:
thislist = ["apple", "banana", "cherry"]
thislist[1] = "blackcurrant"
print(thislist)
ssg 33
PYTHON LISTS
Change a Range of Item Values
• To change the value of items within a specific range, define a list with
the new values, and refer to the range of index numbers where you
want to insert the new values:
• Example
Change the values "banana" and "cherry" with the values
"blackcurrant" and "watermelon":
• thislist = ["apple", "banana", "cherry", "orange", "kiwi", "mango"]
thislist[1:3] = ["blackcurrant", "watermelon"]
print(thislist)
ssg 34
PYTHON LISTS
If you insert more items than you replace, the new items will be
inserted where you specified, and the remaining items will move
accordingly:
Example:
Change the second value by replacing it with two new values:
• thislist = ["apple", "banana", "cherry"]
thislist[1:2] = ["blackcurrant", "watermelon"]
print(thislist)
ssg 35
PYTHON LISTS
If you insert less items than you replace, the new items will be inserted
where you specified, and the remaining items will move accordingly:
Example
• Change the second and third value by replacing it with one value:
• thislist = ["apple", "banana", "cherry"]
thislist[1:3] = ["watermelon"]
print(thislist)
ssg 36
PYTHON LISTS
append() - Add an element to the end of the list
ssg 37
PYTHON LISTS
lst = [1, 2, 3]
lst.append('Alice')
print(lst)
lst.insert(len(lst), 'Bob')
print(lst)
ssg 38
PYTHON LISTS
• What is extend() in Python?
Iterates over its argument and adding each element to the list and extending
the list. The length of the list increases by a number of elements in its
argument.
ssg 39
PYTHON LISTS
• the remove() method removes the first matching value, and not a
specified index;
• the pop() method removes the item at a specified index, and returns
it; and finally the
• del operator just deletes the item at a specified index ( or a range of
indices).
ssg 40
PYTHON LISTS
The del keyword also removes the specified index:
ssg 41
PYTHON LISTS
• thislist = ["apple", "banana", "cherry"]
thislist.remove("banana")
print(thislist)
ssg 42
PYTHON LISTS
ssg 43
PYTHON LISTS
• You can loop through the list items by using a for loop:
ssg 44
PYTHON LISTS
• Example
• Print all items by referring to their index number:
• thislist = ["apple", "banana", "cherry"]
for i in range(len(thislist)):
print(thislist[i])
ssg 45
PYTHON LISTS
Sort the list alphabetically:
thislist = ["orange", "mango", "kiwi", "pineapple", "banana"]
thislist.sort()
print(thislist)
ssg 46
PYTHON LISTS
• Sort the list numerically:
• thislist = [100, 50, 65, 82, 23]
thislist.sort()
print(thislist)
• Example
Sort the list descending:
• thislist = ["orange", "mango", "kiwi", "pineapple", "banana"]
thislist.sort(reverse = True)
print(thislist)
ssg 47
PYTHON LISTS
Make a copy of a list with the copy() method:
thislist = ["apple", "banana", "cherry"]
mylist = thislist.copy()
print(mylist)
ssg 48
PYTHON LISTS
continued……………………
ssg 49
PYTHON LISTS
ssg 50
PYTHON LISTS
Example 1: Find the index of the element
# vowels list
vowels = ['a', 'e', 'i', 'o', 'i', 'u']
# index of 'e' in vowels
index = vowels. index('e')
print('The index of e:', index)
# element 'i' is searched
# index of the first 'i' is returned
index = vowels. index('i')
print('The index of i:', index)
ssg 51
Python Lists
make a list with each item being increasing power of 2
numbers=[2,4,6,8,10]
num=[]
n=0
for n in numbers:
num.append(n**2)
print("original list",numbers)
print("sqarelist",num)
ssg 52
Python List
make a list with each item being increasing power of 2
numbers=[2,4,6,8,10]
num=[]
n=0
for n in numbers:
num.append(n**2)
print("original list",numbers)
print("sqarelist",num)
ssg 53
Python Lists
Stepping
The slicer can take an optional third argument.
which sets interval at which elements are included in the slice.
mylist=['a','c','g','i','a','e','o','i','u’]
print(mylist[1::2])
Output:
['c', 'i', 'e', 'i’]
print(mylist[1::3])
['c', 'a', 'i']
ssg 54
Python List
#odd numbers with in a range
start=4
end=25
for i in range(start,end+1):
if (i%2!=0):
print(i, end = " ")
ssg 55
Python Lists
• Join / Merge two lists in python using + operator
ssg 56
Python List
Join / Merge two lists in python using + operator
list1=['python','programming','c','learning']
list2=[1,2,3,4]
list3=list1+list2
print(list3)
print('Merged list')
list1.extend(list2)
print(list1)
ssg 57
Python List
• Join / Merge two lists in python using unpacking
# Merge two lists
list1=['python','programming','c','learning']
list2=[1,2,3,4]
finallist = [*list1, *list2]
print(finallist)
ssg 58
Python List
Join / Merge two lists in python using list.extend()
list1=['python','programming','c','learning']
list2=[1,2,3,4]
print('Merged list')
list1.extend(list2)
print(list1)
ssg 59
Python List
Join / Merge two lists in python using for loop
list2=["fool","robot","home"]
list3=[23,67,34,89]
for elem in list2:
list3.append(elem)
print("Extended list")
print(list3)
ssg 60
Python List
import itertools
# List of strings
• list_1 = ["This" , "is", "a", "sample", "program"]
• # List of ints
• list_2 = [10, 2, 45, 3, 5, 7, 8, 10]
• # Join two lists
• final_list=list(itertools.chain(list_1, list_2))
• print('Merged List:')
• print(final_list)
ssg 61
Python List
List membership Test.
(list_element) in (list_variable_name)
(list_element) not in (list_variable_name)
#Test 3 is in list
number=[1,2,3]
print('3 in number',3 in number)
print('6 in number',6 in number)
Output:
3 in number True
6 in number False
ssg 62
PYTHON TUPLE
• Tuple
• Tuples are used to store multiple items in a single variable.
• Tuple is one of 4 built-in data types in Python used to store
collections of data, the other 3 are List, Set, and Dictionary, all with
different qualities and usage.
• A tuple is a collection which is ordered and unchangeable.
ssg 63
Tuple Items
Tuple items are indexed, the first item has index [0], the
second item has index [1] etc.
• Ordered
• When we say that tuples are ordered, it means that the items have a
defined order, and that order will not change
ssg 64
Tuple Items
Unchangeable
• Tuples are unchangeable, meaning that we cannot change, add or
remove items after the tuple has been created.
ssg 65
Tuple
• Allow Duplicates
• Since tuples are indexed, they can have items with the same value:
Tuple Length
• To determine how many items a tuple has, use the len() function:
• Create Tuple With One Item
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.
ssg 66
Tuple
• thistuple = ("apple",)
print(type(thistuple))
#NOT a tuple
thistuple = ("apple")
print(type(thistuple))
ssg 67
Tuple
• # nested tuple
• my_tuple = ("mouse", [8, 4, 6], (1, 2, 3))
• print(my_tuple)
ssg 69
Python tuples
• Negative Indexing
• Python allows negative indexing for its sequences.
• The index of -1 refers to the last item, -2 to the second last item and
so on.
ssg 70
Python tuples
• # Negative indexing for accessing tuple elements
• my_tuple = ('p', 'e', 'r', 'm', 'i', 't')
• print(my_tuple[-1])
• # Output: 't'
• print(my_tuple[-6])
• # Output: 'p'
ssg 71
Python tuples
# Accessing tuple elements using slicing
• my_tuple = ('p','y','t','h','o','n','p','r','o','g','r','a','m')
• print(my_tuple[1:4])
• print(my_tuple[:-7])
• print(my_tuple[:7])
• # elements 7th to end
• print(my_tuple[6:])
ssg 72
Tuples and Lists
• Tuples and Lists: differences
• They are both used to store collection of data
• They are both heterogeneous data types means that you can
store any kind of data type
• They are both ordered means the order in which you put the
items are kept.
• They are both sequential data types so you can iterate over the
items contained.
• Items of both types can be accessed by an integer index
operator, provided in square brackets, [index]
ssg 73
Tuples and Lists
• As lists are mutable, Python needs to allocate an extra memory
block in case there is a need to extend the size of the list object
after it is created. In contrary, as tuples are immutable and fixed
size, Python allocates just the minimum memory block required
for the data.
• As a result, tuples are more memory efficient than the lists.
ssg 74
Tuples and Lists
• import sys
a_list = list()
a_tuple = tuple()
a_list = [1,2,3,4,5]
a_tuple = (1,2,3,4,5)
print(sys.getsizeof(a_list))
print(sys.getsizeof(a_tuple))
Output:
104 (bytes for the list object)
88 (bytes for the tuple object)
ssg 75
Python tuples
• Changing tuple values
mytuple = (4, 2, 3, [6, 5])
print(mytuple)
mytuple = (4, 1, 3, [7, 9])
print(mytuple)
mytuple[3][0]=22
mytuple[2]=55
print(mytuple)
ssg 76
Python tuples
mytuple=(3,7,9,6)
mytuple1=(31,72,95,61)
print((mytuple)*3)
m1=mytuple+mytuple1
print(m1)
ssg 77
Python tuples
• mytuple=(3,7,9,6)
• mytuple1=(31,72,95,61)
• print((mytuple)*3)
• m1=mytuple+mytuple1
• print(m1)
ssg 78
Python tuples
As discussed above, we cannot change the elements in a tuple. It means that we cannot delete or remove items
from a tuple.
Deleting a tuple entirely, however, is possible using the keyword del.
# Deleting tuples
my_tuple = ('p', 'r', 'o', 'g', 'r', 'a', 'm')
can't delete items
TypeError: 'tuple' object doesn't support item deletion
del my_tuple[3]
ssg 79
Python Dictionary
Dictionary
• Dictionaries are used to store data values in key:value pairs.
• A dictionary is a collection which is ordered*, changeable and do not allow
duplicates.
• Dictionaries are written with curly brackets, and have keys and values:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
print(thisdict)
ssg 80
Python Dictionary
• Dictionary Items
• Dictionary items are ordered, changeable, and does not allow
duplicates.
• Dictionary items are presented in key:value pairs, and can be referred
to by using the key name.
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
print(thisdict["brand"])
ssg 81
Python Dictionary
• Ordered or Unordered?
• When we say that dictionaries are ordered, it means that the items have a defined order, and that
order will not change.
• Unordered means that the items does not have a defined order, you cannot refer to an item by
using an index.
• As of Python version 3.7, dictionaries are ordered. In Python 3.6 and earlier, dictionaries
are unordered.
• Changeable
• Dictionaries are changeable, meaning that we can change, add or remove items after the dictionary
has been created.
•
Duplicates Not Allowed
• Dictionaries cannot have two items with the same key:
ssg 82
Python Dictionary
Changeable:
Dictionaries are changeable, meaning that we can change, add or remove
items after the dictionary has been created.
Duplicates Not Allowed
• Dictionaries cannot have two items with the same key:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964,
"year": 2020
}
print(thisdict)
ssg 83
Python Dictionary
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964,
"year":2010
}
• print(thisdict)
• print(len(thisdict))
ssg 84
Python Dictionary
ssg 85
Python Dictionary
Accessing Items:
• You can access the items of a dictionary by referring to its key name,
inside square brackets:
ssg 86
Python Dictionary
• Adding Items
Adding an item to the dictionary is done by using a new index key and assigning a value to it:
dict = {
"brand": "MARUTI",
"model": "XL",
"year": 1969
}
#adding item
dict["color"]="Yellow"
print(dict)
#Updating item
dict.update({"color": "blue"})
print(dict)
ssg 87
Python Dictionary
• Update Dictionary
• The update() method will update the dictionary with the items from a
given argument. If the item does not exist, the item will be added.
• The argument must be a dictionary, or an iterable object with
key:value pairs.
ssg 88
Python Dictionary
• Removing Items
• There are several methods to remove items from a dictionary:
• The pop() method removes the item with the specified
key name:
ssg 89
Python Dictionary
• dict = {
"brand": "MARUTI",
"model": "XL",
"year": 1969
}
#adding key and value
dict["color"]="Yellow"
print(dict)
#updating item
dict.update({"color": "blue"})
print(dict)
#removing item
dict.pop("model")
ssg 90
Python Dictionary
Loop Through a Dictionary
• You can loop through a dictionary by using a for loop.
• When looping through a dictionary, the return value are the keys of
the dictionary, but there are methods to return the values as well.
• Print all key names in the dictionary, one by one:
for x in thisdict:
print(x)
ssg 91
Python Dictionary
Print all key names in the dictionary, one by one:
dict = {
"brand": "MARUTI",
"model": "XL",
"year": 1969
}
for x in dict:
print(x)
Output:
• brand
• model
• year
ssg 92
Python Dictionary
ssg 93
Python Dictionary
• You can use the keys() method to return the keys of a
dictionary:
for x in dict.keys():
print(x)
ssg 94
Python Dictionary
You can also use the values() method to return values of a dictionary:
for x in dict.values():
print(x)
Loop through both keys and values, by using the items() method:
for x, y in dict.items():
print(x, y)
ssg 95
Python Dictionary
You cannot copy a dictionary simply by typing dict2 = dict1, because: dict2 will only be a reference to dict1,
and changes made in dict1 will automatically also be made in dict2.
There are ways to make a copy, one way is to use the built-in Dictionary method copy().
ssg 96
Python Dictionary
mydict =dict.copy()
print(mydict)
ssg 97
Python Dictionary
mydict = {
"brand": "MARUTI",
"model": "XL",
"year": 1969
}
mydict1 = dict(mydict)
print(mydict1)
ssg 98
Python Dictionary
The clear() method removes all items from the dictionary.
• print(numbers)
• # Output: {}
ssg 99
Python Dictionary
The any() function returns True if any item in an iterable are true, otherwise it returns False.
If the iterable object is empty, the any() function will return False.
# For dictionaries the any() function checks the keys, not the values.
ssg 100
Python Dictionary
mydict = {0 : "Apple", 1 : "Orange"}
x = all(mydict)
if all items in a set are True:
Check myset = {0, 1, 0}
x = all(myset)
• # Returns False because both the first and the third items are False
ssg 101
Python Dictionary
numbers = [5, 3, 4, 3, 6, 7, 3, 2, 3, 4, 1]
print(sorted(numbers))
ssg 102
Python Dictionary
• words = ["aa", "ab", "ac", "ba", "cb", "ca"]
• sorted(words)
• print(words)
ssg 103
Python Dictionary
• The method cmp() compares two dictionaries based on key and
values.
• cmp(dict1, dict2)
• Return Value
• This method returns 0 if both dictionaries are equal, -1 if dict1 < dict2
and 1 if dict1 > dic2.
ssg 104