0% found this document useful (0 votes)
1 views28 pages

Python 3rd

The document provides an overview of list operations in Python, including mutable and immutable operations, slicing, looping, mutability, aliasing, and cloning. It explains various methods such as append, extend, remove, and reverse for modifying lists, as well as techniques for iterating through lists. Additionally, it discusses the concept of mutability and demonstrates how to clone lists using different approaches.

Uploaded by

Deeksha Magarde
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1 views28 pages

Python 3rd

The document provides an overview of list operations in Python, including mutable and immutable operations, slicing, looping, mutability, aliasing, and cloning. It explains various methods such as append, extend, remove, and reverse for modifying lists, as well as techniques for iterating through lists. Additionally, it discusses the concept of mutability and demonstrates how to clone lists using different approaches.

Uploaded by

Deeksha Magarde
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 28

Q.

1 Demonstrate list operations with example


list operations: List is a type of data structuring method that allows storing of the integers or the
characters in an order indexed by starting from 0. List operations are the operations that can be
performed on the data in the list data structure.

Create Python Lists


# list of integers
my_list = [1, 2, 3]

List Operations in Python


1. Mutable operations

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 = ["apple", "banana", "cherry"]

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()

The min() method returns the minimum value in the list.


Syntax:
print(min(myList))

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

3. index:Returns the position in the list of the specified element.

x = [10, 30, 20]

print(x.index(30))

print(x)

Output:1[10, 30, 20]

4.count:Returns the number of times the specified item occurs in the list.

x = [10, 30, 20, 30, 30]

print(x.count(30))

print(x)

Output:

[10, 30, 20, 30, 30]

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

L = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i']

print(L[2:7])

Output:

['c', 'd', 'e', 'f', 'g']


Slice with Positive & Negative Indices

You can specify both positive and negative indices at the same time.

L = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i']

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:

fruits = ["Apple", "Mango", "Banana", "Peach"]

for fruit in fruits:

print(fruit)

output:

Apple
Mango
Banana
Peach

1. List Comprehension using for loop


List comprehension is similar to the for loop; however, it allows us to create a list and iterate
through it in a single line. Due to its utter simplicity, this method is considered one of the most
robust ways of iterating over Python lists.

Example:
fruits = ["Apple", "Mango", "Banana", "Peach"]
[print(fruit + " juice") for fruit in fruits]

output:

Apple juice
Mango juice
Banana juice
Peach juice

2. A for Loop with range()


Another method for looping through a Python list is the range() function along with
a for loop. range() generates a sequence of integers from the provided starting and stopping
indexes.
Syntax:
range(start, stop, step)

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"]

for index, element in enumerate(fruits):


print(index, ":", element)

Output:

0 : Apple
1 : Mango
2 : Banana
3 : Peach

4. A for Loop with lambda


Python’s lambda function is an anonymous function in which a mathematical expression is
evaluated and then returned. As a result, lambda can be used as a function object. Let’s see how
to use lambda as we loop through a list.We’ll make a for loop to iterate over a list of numbers,
find each number's square, and save or append it to the list. Finally, we’ll print a list of squares.

Example:
lst1 = [1, 2, 3, 4, 5]
lst2 = []

# Lambda function to square number


temp = lambda i:i**2
for i in lst1:
# Add to lst2
lst2.append(temp(i))
print(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.

2. values can be changed in mutable data types

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.

Examples of Mutable Data Types in Python

There are basically 3 mutable data types in Python:

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]

# using append operation in our list


my_list.append(10)
# printing our list after the operation
print("List after appending a value = ",my_list)

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.

Function aliasing in Python


In function aliasing, we create a new variable and assign the function reference to one existing
function to the variable. We can verify that both the objects pointing to the same memory
location using id() built-in function in Python.
Example
def fun(name):
print(f"Hello {name}, welcome to BIST!!!")
cheer = fun
print(f'The id of fun() : {id(fun)}')
print(f'The id of cheer() : {id(cheer)}')
fun('SABA')
cheer('SABA')
Output:
The id of fun() : 140716797521432
The id of cheer() : 140716797521432
Hello SABAs, welcome to BIST!!!
Hello SABA, welcome to BIST!!!
Explanation: In the above example, only one function is available, but we can call that function by using
either fun or cheer name.

Q.6 Demonstrate cloning lists in python


If we want to modify a list and also keep a copy of the original, we need to be able to make a
copy of the list itself, not just the reference. This process is sometimes called cloning, to avoid
the ambiguity of the word copy.The easiest way to clone a list is to use the slice operator.
Taking any slice of a creates a new list. In this case the slice happens to consist of the whole list.

For cloning a list in Python we can follow these approaches-

1. By following the Slicing technique


2. By using extend() method
3. By using list() method
4. By using list comprehension
5. By using append() method
6. By using copy() method
1: Slicing Technique
We will use list slicing technique to access and copy the list elements in another list. This is the
easiest method to modify any list and make a copy of the list along with the reference. This
method takes about 0.039 seconds and is the fastest in 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
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:

Enter size of list 5


Enter element of list 3
Enter element of list 6
Enter element of list 1
Enter element of list 2
Enter element of list 3
Original list: [3, 6, 1, 2, 3]
After cloning: [3, 6, 1, 2, 3]

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:

Enter size of list 6


Enter element of list 3
Enter element of list 5
Enter element of list 12
Enter element of list 78
Enter element of list 16
Enter element of list 35
Original list: [3, 5, 12, 78, 16, 35]
After cloning: [3, 5, 12, 78, 16, 35]

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)

print("After cloning: ",list_copy)

Output:

Enter size of list 4


Enter element of list 2
Enter element of list 7
Enter element of list 9
Enter element of list 10
Original list: [2, 7, 9, 10]
After cloning: [2, 7, 9, 10]
4: list comprehension
In this approach, we will use the list comprehension method. List comprehension is a shorter
syntax for creating a new list based on the values of an existing list. We can create a copy of the
list using list comprehension. The method takes about 0.217 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- Use list comprehension to copy the elements in the list
Step 4- All the values in the original list will be stored in the new list
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 = [ num for num in li ]

print("After cloning: ",list_copy)

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)

print("After cloning: ",list_copy)

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()

print("After cloning: ",list_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]

Q.6 Demonstrate list parameters in python

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.

Q.7 Demonstrate tuple Assignment in python

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.

1.Tuple Packing (Creating Tuples)

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:

>>>tup = (22, 33, 5, 23)


>>>tup
Output:
(22, 33, 5, 23)

2. Tuple Assignment (Unpacking)


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.

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.

Using generator function

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

def Game(sports, players):

#creating the tuple

yield (sports[0], players[0])

yield (sports[1], players[1])

tup1, tup2 = Game(['Cricket', 'Football'], ['Sachin Tendulkar', 'Cristiano Ronaldo'])

print('The first tuple is:',tup1)

print('The second tuple is:',tup2)

Output

Following is an output of the above code −

The first tuple is: ('Cricket', 'Sachin Tendulkar')

The second tuple is: ('Football', 'Cristiano Ronaldo')

Using return statement having return value

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):

# Returning the area and perimeter of a rectangle

area = l*w

perimeter = 2*(l+w)

return (area, perimeter)

print('The area and perimeter of the rectangle is:',Rectangle(21, 43))

Output:

Following is an output of the above code −

The area and perimeter of the rectangle is: (903, 128)


Q.8 Demonstrate Python Dictionary method and operation in python

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.

Functions Name Description


clear() Removes all items from the dictionary
copy() Returns a shallow copy of the dictionary
fromkeys() Creates a dictionary from the given sequence
get() Returns the value for the given key
items() Return the list with all dictionary keys with values
keys() Returns a view object that displays a list of all the keys in the dictionary in
order of insertion
pop() Returns and removes the element with the given key
popitem() Returns and removes the key-value pair from the dictionary
setdefault() Returns the value of a key if the key is in the dictionary else inserts the key
with a value to the dictionary
update() Updates the dictionary with the elements from another dictionary
values() Returns a list of all the values available in a given dictionary

1.clear():The clear() method removes all items from the dictionary.


Syntax:
dict.clear()

Example:
# Python program to demonstrate working of
# dictionary clear()
text = {1: "geeks", 2: "for"}

text.clear()
print('text =', text)

output:
text = {}

2.copy(): method returns a shallow copy of the dictionary.


Syntax: dict.copy()
Example:
original = {1: 'geeks', 2: 'for'}
# copying using copy() function
new = original.copy()
# removing all elements from the list
# Only new list becomes empty as copy()
# does shallow copy.
new.clear()
print('new: ', new)
print('original: ', original)

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.

Syntax : dict.pop(key, def)

Parameters :

key : The key whose key-value pair has to be returned and removed.

def : The default value to return if specified key is not present.

Returns : Value associated to deleted key-value pair, if key is present.

Example:

# Python 3 code to demonstrate


# working of pop()

# initializing dictionary
test_dict = {"Nikhil": 7, "Akshat": 1, "Akash": 2}

# Printing initial dict


print("The dictionary before deletion : " + str(test_dict))

# using pop to return and remove key-value pair.


pop_ele = test_dict.pop('Akash')

# Printing the value associated to popped key


print("Value associated to popped key is : " + str(pop_ele))

# Printing dictionary after deletion


print("Dictionary after deletion is : " + str(test_dict))

Output: The dictionary before deletion : {'Nikhil': 7, 'Akshat': 1, 'Akash': 2}

Value associated to popped key is : 2

Dictionary after deletion is : {'Nikhil': 7, 'Akshat': 1}


Q.9 Explain Python Advanced list

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.

1) Python Sort List


The sort() method is used to sort the elements in a specific order i.e. Ascending or Descending.

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:

Students = ['Harsh', 'Andrew', 'Danny']


print(sorted(Students))
print(Students)
Output:
[‘Andrew’, ‘Danny’, ‘Harsh’]
[‘Harsh’, ‘Andrew’, ‘Danny’]

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:

[‘Andrew’, ‘Danny’, ‘Harsh’]


[‘Harsh’, ‘Andrew’, ‘Danny’]

3) Python Reverse List

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 = ['Harsh', 'Andrew', 'Danny']

Students.reverse()

print(Students)

Output:

[‘Danny’, ‘Andrew’, ‘Harsh’]

4) Python List Index

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:

Value Error: ‘Vammy’ is not in the list


5) Python Copy List

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:
:

my_foods = ['pizza', 'falafel', 'carrot cake']

friend_foods = my_foods[:]

print("My favorite foods are:")

print(my_foods)

print("\nMy friend's favorite foods are:")

print(friend_foods)

Output:

My favorite foods are:


[‘pizza’, ‘falafel’, ‘carrot cake’]

My friend’s favorite foods are:


[‘pizza’, ‘falafel’, ‘carrot cake’]
Q .10 Evaluate list comprehension in python

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.

Advantages of List Comprehension


3. More time-efficient and space-efficient than loops.
4. Require fewer lines of code.
5. Transforms iterative statement into a formula.
6. Syntax of List Comprehension
7. newList = [ expression(element) for element in oldList if condition ]
8. Example of List Comprehension in Python

Example

# Using list comprehension to iterate through loop


List = [character for character in [1, 2, 3]]

# Displaying list
print(List)

Output:
[1, 2, 3]

List Comprehension vs For Loop in Python


Suppose, we want to separate the letters of the word human and add the letters as items of a list.
The first thing that comes in mind would be using for loop.

Example
h_letters = []
for letter in 'human':
h_letters.append(letter)
print(h_letters)

output:
['h', 'u', 'm', 'a', 'n']
.

Example 2: Iterating through a string Using List Comprehension


h_letters = [ letter for letter in 'human' ]
print( h_letters)

output:
['h', 'u', 'm', 'a', 'n']
Practical

9. Write a program for selection sort in python

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:

[5, 7, 20, 30, 50]


2. Write a program for bubble sort in python

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:

[0, 4, 5, 7, 10, 12]


3. Write a program for insertion sort in python

x=[20,10,34,56,40]

for i in range(1,len(x)):

c=i

while c>0 and x[i]<x[i-1]:

a=x[c]

x[c]=x[c-1]

x[c-1]=a

print(x)

Output:

[10, 20, 34, 40, 56]

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy