Python 3rd
Python 3rd
1. append()
The append() method is used to add elements at the end of the list. This method can only add a
single element at a time. To add multiple elements, the append() method can be used inside a
loop.
Syntax:
list.append(iterable)
For Example:
fruits.append("orange")
print(fruits)
Output:
["apple", "banana", "cherry","orange"]
2. extend()
The extend() method is used to add more than one element at the end of the list. Although it can
add more than one element, unlike append(), it adds them at the end of the list like append().
Syntax:
list.extend(iterable)
For Example:
l = [1, 2, 3]
l.extend([4, 5, 6])
print(l)
3. remove()
The remove() method is used to remove an element from the list. In the case of multiple
occurrences of the same element, only the first occurrence is removed.
Code:
myList.remove('makes learning fun!')
myList.insert(4, 'makes')
myList.insert(5, 'learning')
myList.insert(6, 'so much fun!')
print(myList)
Output:
4. reverse()
The reverse() operation is used to reverse the elements of the list. This method modifies the
original list. To reverse a list without modifying the original one, we use the slice operation with
negative indices. Specifying negative indices iterates the list from the rear end to the front end of
the list.
For Example:
print(myList[::-1]) # does not modify the original list
myList.reverse() # modifies the original list
print(myList)
OUTPUT:
5.del: Deletes the element located in the specific index. This method also has the possibility to
remove a section of elements from the list, through the “:” operator. You only need to define a
starting and end point [start:end], keep in mind that the end point will not be considered.
Example:
x = [1, 2, 3]
del x[1]
print(x)
Output:[1, 3]
2. Immutable operations
1. min()
Example:
print(min([1, 2, 3]))
output:1
2.max(): The max() method returns the maximum value in the list. Both the methods accept only
homogeneous lists, i.e. lists having elements of similar type.
Example:
print(max([1, 2, 3])
Output:3
print(x.index(30))
print(x)
4.count:Returns the number of times the specified item occurs in the list.
print(x.count(30))
print(x)
Output:
5. sum
This method sums the items of the list, just if they can be summed. Sum is a widely used method
with numeric type lists.
x = [2.5, 3, 3.5]
print(sum(x))
print(x)
Output:
9.0
[2.5, 3, 3.5]
Q.2 Demonstrate list slice function and with an illustration?
Python slice() function is used to get a slice of elements from the collection of elements. Python
provides two overloaded slice functions. The first function takes a single argument while the second
function takes three arguments and returns a slice object.
Signature
slice (stop)
slice (start, stop[, step])
Parameters
start: Starting index of slicing.
stop: End index of the slice
step: The number of steps to jump.
Example:
a = ("a", "b", "c", "d", "e", "f", "g", "h")
x = slice(3, 5)
print(a[x])
output:
('d', 'e')
Slicing a List
To access a range of items in a list, you need to slice a list. One way to do this is to use the
simple slicing operator :With this operator you can specify where to start the slicing, where
to end and specify the step.
If L is a list, the expression L [ start : stop : step ] returns the portion of the list from
index start to index stop, at a step size step.
Syntax
print(L[2:7])
Output:
You can specify both positive and negative indices at the same time.
print(L[2:-5])
Output:
['c', 'd']
Q.3 Demonstrate list loop in python
Using a Python for loop is one of the simplest methods for iterating over a list or any other
sequence (e.g. TUPLES, SETS, OR DICTIONARIES).python for loops are a powerful tool, so it
is important for programmers to understand their versatility. We can use them to run the
statements contained within the loop once for each item in a list. For example:
print(fruit)
output:
Apple
Mango
Banana
Peach
Example:
fruits = ["Apple", "Mango", "Banana", "Peach"]
[print(fruit + " juice") for fruit in fruits]
output:
Apple juice
Mango juice
Banana juice
Peach juice
Example:
fruits = ["Apple", "Mango", "Banana", "Peach"]
# Constructs range object containing elements from 0 to 3
for i in range(len(fruits)):
print("The list at index", i, "contains a", fruits[i])
output:
The list at index 0 contains a Apple
The list at index 1 contains a Mango
The list at index 2 contains a Banana
The list at index 3 contains a Peach
3. A for Loop with enumerate()
Sometimes you want to know the index of the element you are accessing in the list.
The enumerate() function will help you here; it adds a counter and returns it as something called
an ‘enumerate object’. This object contains elements that can be unpacked using a simple Python
for loop. Thus, an enumerate object reduces the overhead of keeping a count of the number of
elements in a simple iteration.
Example:
fruits = ["Apple", "Mango", "Banana", "Peach"]
Output:
0 : Apple
1 : Mango
2 : Banana
3 : Peach
Example:
lst1 = [1, 2, 3, 4, 5]
lst2 = []
output:
[1, 4, 9, 16, 25]
Q.4 What is mutability?
In technical programming terms, a mutable object is an object whose state can be modified after
it is defined. The opposite of a mutable object is an immutable object, whose state cannot be
altered after it is initially defined.Examples of immutable objects in Python include integers,
floats, strings, and tuples. The two types of mutable objects you’ll likely deal with most often
when programming in Python are lists and dictionaries.Basically, mutable data types in Python
are those whose value can be changed in place after they have been created.
1. What is "in-place" ?
By in-place, we mean that, any operation that changes the content of anything without making a
separate copy of it. For example, we can directly add, remove, or update the values of a list in
Python, without creating a new list.
For example, in the above image, we are able to append new values to our list lst without having
to create another list. Hence we can overwrite the original list. Hence, it is an in-place operation.
In mutable data types, we can modify the already existing values of the data types (such as lists,
dictionaries, etc.). Or, we may add new values or remove the existing values from our data types.
Basically, we may perform any operation with our data without having to create a new copy of
our data type. Hence, the value assigned to any variable can be changed.
1. List
2. Dictionary
3. Set
1. List:
A list data structure is a ordered sequence of elements in Python, that is mutable, or changeable.
This is because we can change the value of a list in Python by assigning a new value to our
already existing list. We need not create any separate (or new) copy of the list to perform these
operations. A few examples for the same are given below.
Example:
my_list = [1,2,3,4,5]
Output:
List after appending a value = [1, 2, 3, 4, 5, 10]
Set: A set is an unordered collection of items in Python. All the elements of the set are unique in
nature, that is, there are no duplicates in a set. Also, the elements of the set are immutable in
nature, that is, they cannot be changed.However, a set itself is mutable in Python.
Example:
my_set = {1,2,6,5,7,11}
# adding an element in our set
my_set.add(16)
# printing our set after the operation
print("Set after adding a value : ",my_set)
output:
Set after adding a value : {1, 2, 5, 6, 7, 11, 16}
3. Dictionary in Python
Dictionary in Python is an unordered collection of items. Each item of a dictionary has a key/value pair,
using which we can access a particular key or value of a dictionary. Keys in dictionaries are unique in
nature.
Example:
my_dict = {"state":"Mp", "City":"bhopal"}
my_dict['Country'] = "India"
# printing our dictionary after the operation
print("adding a new key-value pair = ",my_dict)
output:
adding a new key-value pair = {'state': 'Mp', 'City': 'bhopal', 'Country': 'India'}
Q.5 Demonstrate Aliasing in python
Aliasing happens when the value of one variable is assigned to another variable because
variables are just names that store references to actual value.
Aliasing means giving another name to the existing object.it doesn’t mean copying.
Example:
L=[1,2,3]
A=L
Print(A)
output:
[1,2,3]
Explanation: From the output of the above program, it is clear that first_variable and
second_variable have the same reference id in memory.So, both variables point to the same
string object ‘PYTHON’.
And in Python programming, when the value of one variable is assigned to another variable,
aliasing occurs in which reference is copied rather than copying the actual value.
Algorithm
Follow the algorithm to understand the approach better.
Step 1- Take input of list from user
Step 2- Declare a new list which will be the copy
Step 3- Copy the elements using slicing operator ( : ) in the new list
Step 4- Print the new list which will be the copy of the original list
Example:
li=[]
n=int(input("Enter size of list "))
for i in range(0,n):
e=int(input("Enter element of list "))
li.append(e)
print("Original list: ",li)
#cloning
list_copy = li[:]
print("After cloning: ",list_copy)
Output:
2: extend()
A list can be copied into a new list by using the in-built extend() function. This will add each
element of the original list to the end of the new list. This method takes around 0.053 seconds to
complete.
Algorithm
Follow the algorithm to understand the approach better.
Step 1- Take input of list from user
Step 2- Declare a new list which will be the copy
Step 3- Copy the elements using extend() in the new list
Step 4- Print the new list which will be the copy of the original list
Example:
Look at the program to understand the implementation of the above-mentioned approach. In this
program, we have input elements of the list from the user and copied it into a new list using the
extend() function.
li=[]
n=int(input("Enter size of list "))
for i in range(0,n):
e=int(input("Enter element of list "))
li.append(e)
print("Original list: ",li)
#cloning
list_copy = []
list_copy.extend(li)
print("After cloning: ",list_copy)
Output:
3: list()
We will simply use the list() function to copy the existing list into another list in this approach.
This method takes about 0.075 seconds to complete.
Algorithm
Follow the algorithm to understand the approach better.
Step 1- Take input of list from user
Step 2- Declare a new list which will be the copy of the original list
Step 3- Initialise the new list and pass the original list in the list() function
Step 4- Print the new list which will be the copy of the original list
Example:
li=[]
n=int(input("Enter size of list "))
for i in range(0,n):
e=int(input("Enter element of list "))
li.append(e)
print("Original list: ",li)
#cloning
list_copy = list(li)
Output:
Example:
li=[]
n=int(input("Enter size of list "))
for i in range(0,n):
e=int(input("Enter element of list "))
li.append(e)
print("Original list: ",li)
#cloning
list_copy = [ num for num in li ]
output:
Enter size of list 7
Enter element of list 12
Enter element of list 13
Enter element of list 2
Enter element of list 24
Enter element of list 6
Enter element of list 35
Enter element of list 8
Original list: [12, 13, 2, 24, 6, 35, 8]
After cloning: [12, 13, 2, 24, 6, 35, 8]
5: append()
append() function simply adds the element to the last position of a list. This can be used for
copying elements to a new list. This method takes around 0.325 seconds to complete and is the
slowest method for cloning a list.
Algorithm
Follow the algorithm to understand the approach better.
Step 1- Take input of list from user
Step 2- Declare a new list which will be the copy of the original list
Step 3- Run a loop to access each element in the list
Step 4- Use append() to add each element in the new list one by one
Step 5- Print the new list which will be the copy of the original list
Example:
li=[]
n=int(input("Enter size of list "))
for i in range(0,n):
e=int(input("Enter element of list "))
li.append(e)
print("Original list: ",li)
#cloning
list_copy = []
for num in li:
list_copy.append(num)
Output:
Enter size of list 8
Enter element of list 2
Enter element of list 3
Enter element of list 4
Enter element of list 5
Enter element of list 6
Enter element of list 8
Enter element of list 9
Enter element of list 10
Original list: [2, 3, 4, 5, 6, 8, 9, 10]
After cloning: [2, 3, 4, 5, 6, 8, 9, 10]
6: copy()
copy() is an in-built method to copy all the elements from one list to another. This method takes
around 1.488 seconds to complete and takes the most time out of all the approaches.
Algorithm
Follow the algorithm to understand the approach better.
Step 1- Take input of list from user
Step 2- Declare a new list
Step 3- copy the original list to the new list using the copy() function
Step 4- Print the new list
Example:
li=[]
n=int(input("Enter size of list "))
for i in range(0,n):
e=int(input("Enter element of list "))
li.append(e)
print("Original list: ",li)
#cloning
list_copy = li.copy()
Output:
Enter size of list 5
Enter element of list 12
Enter element of list 13
Enter element of list 14
Enter element of list 25
Enter element of list 26
Original list: [12, 13, 14, 25, 26]
After cloning: [12, 13, 14, 25, 26]
Functions which take lists as arguments and change them during execution are
called modifiers and the changes they make are called side effects. Passing a list as an argument
actually passes a reference to the list, not a copy of the list. Since lists are mutable, changes made
to the elements referenced by the parameter change the same list that the argument is referencing.
Example:
def doubleStuff(aList):
""" Overwrite each element in aList with double its value. """
for position in range(len(aList)):
aList[position] = 2 * aList[position]
things = [2, 5, 9]
print(things)
doubleStuff(things)
print(things)
Output:
[2, 5, 9]
[4, 10, 18]
The parameter aList and the variable things are aliases for the same object.
Since the list object is shared by two references, there is only one copy. If a function modifies the
elements of a list parameter, the caller sees the change since the change is occurring to the
original.
This can be easily seen in codelens. Note that after the call to doubleStuff, the formal
parameter aList refers to the same object as the actual parameter things. There is only one copy
of the list object itself.
tuple Assignment
In python, we can perform tuple assignment which is a quite useful feature. We can initialise or
create a tuple in various ways. Besides tuple assignment is a special feature in python. We also
call this feature unpacking of tuple.
The process of assigning values to a tuple is known as packing. While on the other hand, the
unpacking or tuple assignment is the process that assigns the values on the right-hand side to the
left-hand side variables. In unpacking, we basically extract the values of the tuple into a single
variable.
Moreover, while performing tuple assignments we should keep in mind that the number of
variables on the left-hand side and the number of values on the right-hand side should be equal.
Or in other words, the number of variables on the left-hand side and the number of elements in
the tuple should be equal. Let us look at a few examples of packing and unpacking.
We can create a tuple in various ways by using different types of elements. Since a tuple can contain all
elements of the same data type as well as of mixed data types as well. Therefore, we have multiple ways
of creating tuples.
Example:
Example:
>>>(n1, n2) = (99, 7)
>>>print(n1)
99
>>>print(n2)
7
Q.8 Demonstrate tuple as return value in python
Tuples allow for the storage of multiple items in a single variable. The tuple is one of Python's
four built-in data structures for storing data collections. It is an established collection that is
ordered cannot be changed.Any object, even a tuple, can be returned by a Python function.
Create the tuple object within the function body, assign it to a variable, and then use the keyword
"return" to return the tuple to the function's caller.
When a generator-function wants to generate a value, it uses the yield keyword rather than the
return keyword when defining it. When yield is present in a def's body, the function transforms
into a generator function.
Example
Output
Functions can return tuples as return values. This is quite helpful since we frequently want to
know a batsman's highest and lowest score, the mean and standard deviation, the year, month,
and day, or if we're conducting some ecological modelling, the number of snakes and the number
of crocodiles on an island at a particular moment. A function (which can only return one value)
can produce a single tuple that contains multiple elements in each scenario.
Example
def Rectangle(l,w):
area = l*w
perimeter = 2*(l+w)
Output:
Python Dictionary is like a map that is used to store data in the form of a key:value pair. Python
provides various in-built functions to deal with dictionaries. In this article, we will see a list of all
the functions provided by Python to work with dictionaries.
Example:
# Python program to demonstrate working of
# dictionary clear()
text = {1: "geeks", 2: "for"}
text.clear()
print('text =', text)
output:
text = {}
output:
new: {}
original: {1: 'geeks', 2: 'for'}
3.fromkeys():Python dictionary fromkeys() function returns the dictionary with key mapped and
specific value. It creates a new dictionary from the given sequence with the specific value.
Syntax:
Syntax : fromkeys(seq, val)
Parameters :
seq : The sequence to be transformed into a dictionary.
val : Initial values that need to be assigned to the generated keys. Defaults to None.
Example:
seq = ('a', 'b', 'c')
print(dict.fromkeys(seq, None))
Output:
{'a': None, 'b': None, 'c': None}
4. pop() method removes and returns the specified element from the dictionary.
Parameters :
key : The key whose key-value pair has to be returned and removed.
Example:
# initializing dictionary
test_dict = {"Nikhil": 7, "Akshat": 1, "Akash": 2}
The concepts in Python Advanced list includes Python Sort Method, Sorted function, Python
Reverse List, Python Index Method, Copying a List, Python Join Function, Sum Function,
Removing duplicates from the List, Python List Comprehension, etc.
If you want to sort the elements in Ascending order, then you can use the following syntax.
list.sort()
If you want to sort the elements in Descending order, then you can use the following syntax.
list.sort(reverse=True)
Example:
Students = ['Harsh', 'Andrew', 'Danny']
Students.sort()
print(Students)
Output:
[‘Andrew’, ‘Danny’, ‘Harsh’]
Now let’s see, How to sort the list in a Descending Order.
Example:
Students = ['Harsh', 'Andrew', 'Danny']
Students.sort()
print(Students)
Output:
[‘Andrew’, ‘Danny’, ‘Harsh’]
2) Sorted function
In order to maintain the original order of the list that is present in sorted order, you can use the
sorted() function. The sorted() function allows you to display your list in a particular order,
without affecting the actual order of the list.
Example:
You can also print the list in a reverse order using the sorted function in the following manner:
Example:
Students = ['Harsh', 'Andrew', 'Danny']
print(sorted(Students))
print(Students)
Output:
In order to reverse the original order of a list, you can use the reverse() method. The reverse() method is
used to reverse the sequence of the list and not to arrange it in a sorted order like the sort() method.
Example:
Students.reverse()
print(Students)
Output:
Index method is used to find a given element in the list and return to its position.
If the same element is present more than once, then it returns the position of the first element. The
index in python starts from 0.
Example:
Students = ['Harsh','Andrew','Danny','Ritesh','Meena']
print(Students.index('Danny'))
Output:
If you search for an element which is not present in the list, then You will get an error.
Example:
:
Students = ['Harsh','Andrew','Danny','Ritesh','Meena']
print(Students.index('Vammy'))
Output:
At times, You may want to start with an existing list and make an entirely new list based on the first
one..In order to copy a list, you can make a slice that includes the complete original list by omitting the
first index and the second index ([:]). This, in turn, will tell Python to make a slice that starts at the first
item and ends with the last item, by producing a copy of the entire list.
Example:
:
friend_foods = my_foods[:]
print(my_foods)
print(friend_foods)
Output:
A Python list comprehension consists of brackets containing the expression, which is executed
for each element along with the for loop to iterate over each element in the Python list.
Python List comprehension provides a much more short syntax for creating a new list based on
the values of an existing list.
Example
# Displaying list
print(List)
Output:
[1, 2, 3]
Example
h_letters = []
for letter in 'human':
h_letters.append(letter)
print(h_letters)
output:
['h', 'u', 'm', 'a', 'n']
.
output:
['h', 'u', 'm', 'a', 'n']
Practical
x=[20,5,7,30,50]
for i in range(0,len(x)-1):
for j in range(i+1,len(x)):
if x[i]>x[j]:
x[i],x[j]=x[j],x[i]
print(x)
Output:
x=[12,5,7,0,4,10]
for i in range(0,len(x)-1):
for j in range(0,len(x)-1):
if x[j]>x[j+1]:
x[j],x[j+1]=x[j+1],x[j]
print(x)
Output:
x=[20,10,34,56,40]
for i in range(1,len(x)):
c=i
a=x[c]
x[c]=x[c-1]
x[c-1]=a
print(x)
Output: