Python Chapter 3 Notes By Ur Engineering Friend
Python Chapter 3 Notes By Ur Engineering Friend
Notes
Lists in Python :
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.
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.
List Items
List items are indexed, the first item has index [0], the second item has index [1]
etc.
Ordered
When we say that lists are ordered, it means that the items have a defined order,
and that order will not change.
If you add new items to a list, the new items will be placed at the end of the list.
Changeable
Allow Duplicates
Since lists are indexed, lists can have items with the same value:
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 −
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 −
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 −
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.
Built-in Functions
1. Compare
Description
Syntax
cmp(list1, list2)
Parameters
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 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.
2. Length
Description
Python list method len() returns the number of elements in the list.
Syntax
len(list)
Parameters
Return Value
Example
3. Maximum
Description
Python list method max returns the elements from the list with maximum value.
Syntax
max(list)
Parameters
Return Value
This method returns the elements from the list with maximum value.
Example
4. Minimum
Description
Python list method min() returns the elements from the list with minimum
value.
Syntax
min(list)
Parameters
Return Value
This method returns the elements from the list with minimum value.
Example
5. List(Sequence)
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
list( seq )
Parameters
Return Value
Example
Tuples in Python :
tup1 = ();
To write a tuple containing a single value you have to include a comma, even
though there is only one value −
Like string indices, tuple indices start at 0, and they can be sliced, concatenated,
and so on.
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[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 −
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 −
This produces the following result. Note an exception raised, this is because
after del tup tuple does not exist any more −
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..
1. Compare
Description
Syntax
cmp(tuple1, tuple2)
Parameters
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 we reached the end of one of the tuples, the longer tuple is "larger." If we
exhaust both tuples and share the same data, the result is a tie, meaning that 0 is
returned.
Example
-1
1
-1
Description
Python tuple method len() returns the number of elements in the tuple.
Syntax
len(tuple)
Parameters
Return Value
Example
Description
Python tuple method max returns the elements from the tuple with maximum
value.
Syntax
max(tuple)
Parameters
Return Value
This method returns the elements from the tuple with maximum value.
Example
Description
Python tuple method min() returns the elements from the tuple with minimum
value.
Syntax
min(tuple)
Parameters
Return Value
This method returns the elements from the tuple with minimum value.
Example
Set Operations
The sets in python are typically used for mathematical operations like union,
intersection, difference and complement etc. We can create a set, access it’s
elements and carry out these mathematical operations as shown below.
Creating a set
A set is created by using the set() function or placing all the elements within a
pair of curly braces.
Days=set(["Mon","Tue","Wed","Thu","Fri","Sat","Sun"])
Months={"Jan","Feb","Mar"}
Dates={21,22,17}
print(Days)
print(Months)
print(Dates)
We cannot access individual values in a set. We can only access all the elements
together as shown above. But we can also get a list of individual elements by
looping through the set.
Days=set(["Mon","Tue","Wed","Thu","Fri","Sat","Sun"])
for d in Days:
print(d)
Wed
Sun
Fri
Tue
Mon
Thu
Sat
Days=set(["Mon","Tue","Wed","Thu","Fri","Sat"])
Days.add("Sun")
print(Days)
Days=set(["Mon","Tue","Wed","Thu","Fri","Sat"])
Days.discard("Sun")
print(Days)
Union of Sets
The union operation on two sets produces a new set containing all the distinct
elements from both the sets. In the below example the element “Wed” is present
in both the sets.
When the above code is executed, it produces the following result. Please note
the result has only one “wed”.
Intersection of Sets
The intersection operation on two sets produces a new set containing only the
common elements from both the sets. In the below example the element “Wed”
is present in both the sets.
DaysA = set(["Mon","Tue","Wed"])
DaysB = set(["Wed","Thu","Fri","Sat","Sun"])
AllDays = DaysA & DaysB
print(AllDays)
When the above code is executed, it produces the following result. Please note
the result has only one “wed”.
set(['Wed'])
Difference of Sets
The difference operation on two sets produces a new set containing only the
elements from the first set and none from the second set. In the below example
DaysA = set(["Mon","Tue","Wed"])
DaysB = set(["Wed","Thu","Fri","Sat","Sun"])
AllDays = DaysA - DaysB
print(AllDays)
When the above code is executed, it produces the following result. Please note
the result has only one “wed”.
set(['Mon', 'Tue'])
Compare Sets
We can check if a given set is a subset or superset of another set. The result is
True or False depending on the elements present in the sets.
DaysA = set(["Mon","Tue","Wed"])
DaysB = set(["Mon","Tue","Wed","Thu","Fri","Sat","Sun"])
SubsetRes = DaysA <= DaysB
SupersetRes = DaysB >= DaysA
print(SubsetRes)
print(SupersetRes)
True
True
Python Dictionary is used to store the data in a key-value pair format. The
dictionary is the data type in Python, which can simulate the real-life data
arrangement where some specific value exists for some particular key. It is the
mutable data-structure. The dictionary is defined into element Keys and values.
In other words, we can say that a dictionary is the collection of key-value pairs
where the value can be any Python object. In contrast, the keys are the
immutable Python object, i.e., Numbers, string, or tuple.
The dictionary can be created by using multiple key-value pairs enclosed with
the curly brackets {}, and each key is separated from its value by the colon
(:).The syntax to define the dictionary is given below.
Syntax:
In the above dictionary Dict, The keys Name and Age are the string that is an
immutable object.
Accessing Items
You can access the items of a dictionary by referring to its key name, inside
square brackets:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = thisdict["model"]
There is also a method called get() that will give you the same result:
Example
x = thisdict.get("model")
Get Keys
The keys() method will return a list of all the keys in the dictionary.
Example
x = thisdict.keys()
Example
Add a new item to the original dictionary, and see that the keys list gets updated
as well:
car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
x = car.keys()
car["color"] = "white"