Python 4
Python 4
List
A list in Python is used to store the sequence of various types of data.
Python lists are mutable types which means we can modify its
element after it is created.
However, Python consists of many data types that are capable to store
the sequences, but the most common and reliable type is the list.
A list can be defined as a collection of values or items of different
types. The items in the list are separated with the comma (,) and
enclosed with the square brackets [].
A list can be define as below
L1 = ["John", 102, "USA"]
L2 = [1, 2, 3, 4, 5, 6]
If we try to print the type of L1, and L2 using type() function then it
will come out to be a list.
print(type(L1))
print(type(L2))
Output:
<class 'list'> <class 'list'>
Characteristics of Lists
Output:
5
[3, 4, 5]
[1, 2, 3, 4]
[3, 4]
Updating List values
Lists are the most versatile data structures in Python since they are
mutable, and their values can be updated by using the slice and
assignment operator.
Python also provides append() and insert() methods, which can be
used to add values to the list.
Consider the following example to update the values inside the list.
list = [1, 2, 3, 4, 5, 6]
print(list)
# It will assign value to the value to the second index
list[2] = 10
print(list)
# Adding multiple-element Output:
[1, 2, 3, 4, 5, 6]
list[1:3] = [89, 78]
[1, 2, 10, 4, 5, 6]
print(list) [1, 89, 78, 4, 5, 6]
# It will add value at the end of the list [1, 89, 78, 4, 5, 25]
list[-1] = 25
print(list)
Python List Operations
The concatenation (+) and repetition (*) operators work in the same way as
they were working with the strings.
Consider a Lists l1 = [1, 2, 3, 4], and l2 = [5, 6, 7, 8]
Output:
John
David
James
Jonathan
Adding elements to the list
Python provides append() function which is used to add an element to the list.
However, the append() function can only add value to the end of the list.
Example:
l =[]
n = int(input("Enter the number of elements in the list:"))
# for loop to take the input
for i in range(0,n):
# The input is taken from the user and added to the list as the item
l.append(input("Enter the item:"))
print("printing the list items..")
for i in l:
print(i, end = " ")
Output:
Enter the number of elements in the list:3
Enter the item:25
Enter the item:46
Enter the item:12
printing the list items.. 25 46 12
Removing elements from the list
Python provides the remove(element) function which is used to
remove the element from the list.
Example -
list = [0,1,2,3,4]
print("printing original list: ");
for i in list:
print(i,end=" ")
list.remove(2)
print("\nprinting the list after the removal of first element...")
for i in list:
print(i,end=" ")
Output:
printing original list: 0 1 2 3 4
printing the list after the removal of first element... 0 1 3 4
Python built-in methods
insert(): Inserts an elements at specified position.
Syntax: list.insert(position, element)
Note: Position mentioned should be within the range
of List, as in this case between 0 and 4, elsewise
would throw IndexError.
List = ['Mathematics', 'chemistry', 1997, 2000]
# Insert at index 2 value 10087
List.insert(2,10087)
print(List)
Output:
['Mathematics', 'chemistry', 10087, 1997, 2000]
extend(): Adds contents of List2 to the end of List1.
Syntax:List1.extend(List2)
List1 = [1, 2, 3]
List2 = [2, 3, 4, 5]
# Add List2 to List1
List1.extend(List2)
print(List1) # [1, 2, 3, 2, 3, 4, 5]
# Add List1 to List2 now
List2.extend(List1)
print(List2)
Output:
[1, 2, 3, 2, 3, 4, 5]
[2, 3, 4, 5, 1, 2, 3, 2, 3, 4, 5]
sum() : Calculates sum of all the elements of List.
Syntax: sum(List)
List = [1, 2, 3, 4, 5]
print(sum(List))
Output:
15
extend() Add the elements of a list (or any iterable), to the end of the
current list
index() Returns the index of the first element with the specified
value
insert(index,value) Adds an element at the specified position
pop() Removes the element at the specified position
reverse() Reverses the order of the list
sort() Sorts the list
max() Returns the maximum value of the list
min() Returns the minimum value of the list
Example: to remove duplicates from list
list=[3,4,4,6,2,3,6,5,2,1,7]
U_list=[]
for i in list:
if i not in U_list:
U_list.append(i)
print(U_list) # [3, 4, 6, 2, 5, 1, 7]
print(my_tuple[0]) # 'p'
print(my_tuple[5]) # 't'
# nested tuple
n_tuple = ("mouse", [8, 4, 6], (1, 2, 3))
# nested index
print(n_tuple[0][3]) # 's'
print(n_tuple[1][1]) #4
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.
Example
# Negative indexing for accessing tuple elements
my_tuple = ('p', 'e', 'r', 'm', 'i', 't')
# Output: 't'
print(my_tuple[-1])
# Output: 'p'
print(my_tuple[-6])
Slicing
We can access a range of items in a tuple by using the
slicing operator colon : .
Slicing can be best visualized by considering the index
to be between the elements as shown below. So if we
want to access a range, we need the index that will slice
the portion from the tuple.
Elemens P R O G A M
Positive Index 0 1 2 3 4 5
Negative Index -6 -5 -4 -3 -2 -1
Example
# Accessing tuple elements using slicing
my_tuple = ('p','r','o','g','r','a','m')
# elements 2nd to 4th
print(my_tuple[1:4]) # Output: ('r', 'o', 'g')
my_tuple[1] = 9
# TypeError: 'tuple' object does not support item assignment
print(my_tuple)
# Output: ('p', 'r', 'o', 'g', 'r', 'a', 'm')
Packing of Tuples
When we create a tuple, we normally assign values to it.
This is called "packing" a tuple:
Example
Packing a tuple:
fruits = ("apple", "banana", "cherry")
Unpack Tuples
In Python, we are also allowed to extract the values back into variables.
This is called "unpacking":
Example
Unpacking a tuple:
fruits = ("apple", "banana", "cherry")
print(green)
print(yellow)
print(red)
OUTPUT:
apple
Banana
cherry
Using Asterisk(*)
If the number of variables is less than the number of values, you can
add an * to the variable name and the values will be assigned to the
variable as a list:
Example
Assign the rest of the values as a list called "red":
fruits = ("apple", "banana", "cherry", "strawberry", "raspberry")
(green, yellow, *red) = fruits
print(green)
print(yellow)
print(red)
OUTPUT:
apple
Banana
['cherry', 'strawberry', 'raspberry‘]
Tuple Operations
Length
Use the len() function to determine the length of the
tuple, then start at 0 and loop your way through the
tuple items by refering to their indexes.
Remember to increase the index by 1 after each
iteration.
Example
Print all items, using a while loop to go through all the
index numbers:
thistuple = ("apple", "banana", "cherry")
i=0
while i < len(thistuple):
print(thistuple[i])
i=i+1
OUTPUT:
apple
banana
cherry
Concatenation
Concatenation of Two Tuples
To join two or more tuples you can use the + operator:
Example
Join two tuples:
tuple1 = ("a", "b" , "c")
tuple2 = (1, 2, 3)
# Creating a Dictionary
# with dict() method
Dict = dict({1: ‘python', 2: ‘high', 3:'Point'})
print("\nCreate Dictionary by using dict(): ")
print(Dict) # {1: ‘python', 2: ‘high', 3:'Point'}
Accessing the dictionary values
We have discussed how the data can be accessed in the
list and string by using the indexing.
However, the values can be accessed in the dictionary by
using the keys as keys are unique in the dictionary.
The dictionary values can be accessed in the following
way.
Employee = {"Name": "John", "Age": 29}
print("printing Employee data .... ")
print("Name : %s" %Employee["Name"])
print("Age : %d" %Employee["Age"])
Output:
printing Employee data ....
Name : John
Adding dictionary values
The dictionary is a mutable data type, and its values can be updated by
using the specific keys.
The value can be updated along with key Dict[key] = value.
Note: If the key-value already present in the dictionary, the value
gets updated. Otherwise, the new keys added in the dictionary.
Let's see an example to update the dictionary values.
# Creating an empty Dictionary
D = {}
# Adding elements to dictionary one at a time
D[0] = 'Peter'
D[7] = 'Joseph'
D[90] = 'Ricky'
print("\nDictionary after adding 3 elements: ")
print(D)
Output:
Dictionary after adding 3 elements:
Deleting elements using del keyword
The items of the dictionary can be deleted by using
the del keyword as given below.
Employee = {"Name": "John", "Age": 29, "salary":25000,"Company"
:"GOOGLE"}
print("Deleting some of the employee data")
del Employee["Name"]
del Employee["Company"]
print("printing the modified information ")
print(Employee)
print("Deleting the dictionary: Employee");
del Employee
print("Lets try to print it again ");
print(Employee)
Output:
Deleting some of the employee data
printing the modified information
{'Age': 29, 'salary': 25000}
Deleting the dictionary: Employee
Lets try to print it again
Traceback (most recent call last):
File "<string>", line 11, in <module>
NameError: name 'Employee' is not defined
Iterating Dictionary
A dictionary can be iterated using for loop as given below.
Example 1
# for loop to print all the keys of a dictionary
Employee = {"Name": "John", "Age": 29, "salary":25000,"Com
pany":"GOOGLE"}
for x in Employee:
print(x)
Output:
Name
Age
salary
Company
Example 2
#for loop to print all the values of the dictionary
Employee = {"Name": "John", "Age": 29, "salary":25000,"C
ompany":"GOOGLE"}
for x in Employee:
print(Employee[x])
Output:
John
29
25000
GOOGLE
Example - 3
#for loop to print the values of the dictionary by
using values() method.
Employee = {"Name": "John", "Age": 29, "salary":25000,"C
ompany":"GOOGLE"}
for x in Employee.values():
print(x)
Output:
John
29
25000
GOOGLE
Example 4
#for loop to print the items of the dictionary by
using items() method.
Employee = {"Name": "John", "Age": 29, "salary":25000,"C
ompany":"GOOGLE"}
for x in Employee.items():
print(x)
Output:
('Name', 'John')
('Age', 29)
('salary', 25000)
('Company', 'GOOGLE')
S. No Function Description
1 dic.clear() It is used to delete all the items of the dictionary.
2 dict.has_key(key) It returns true if the dictionary contains the
specified key.
3 dict.items() It returns all the key-value pairs as a tuple.
4 dict.keys() It returns all the keys of the dictionary.
5 dict.update(dict2) It updates the dictionary by adding the key-value
pair of dict2 to this dictionary.
6 dict.values() It returns all the values of the dictionary.
7 len() It returns length of the dictionary.
8 popItem() method removes the item that was last inserted
into the dictionary
9 pop() method removes the item usinh key from the
dictionary
Set
A set is a collection of the unordered items.
Each element in the set must be unique, immutable, and
the sets remove the duplicate elements.
Sets are mutable which means we can modify them after
their creation.
The set can be created by enclosing the comma-separated
immutable items with the curly braces {}.
Days = {"Monday", "Tuesday", "Wednesday", "Thursday",
"Friday", "Saturday", "Sunday"}
print(Days)
print(type(Days))
print("looping through the set elements ... ")
for i in Days:
print(i)
Using set() method
Days = set(["Monday", "Tuesday", "Wednesday", "Thursday
", "Friday", "Saturday", "Sunday"])
print(Days)
print(type(Days))
print("looping through the set elements ... ")
for i in Days:
print(i)
add() method
Months = set(["January","February", "March", "April", "May"
, "June"])
print("\nprinting the original set ... ")
print(months)
print("\nAdding other months to the set...");
Months.add("July");
Months.add ("August");
print("\nPrinting the modified set...");
print(Months)
print("\nlooping through the set elements ... ")
for i in Months:
print(i)
update() function
Months = set(["January","February", "March", "April", "Ma
y", "June"])
print("\nprinting the original set ... ")
print(Months)
print("\nupdating the original set ... ")
Months.update(["July","August","September","October"]);