0% found this document useful (0 votes)
23 views

Assignment 2

The document is an assignment on Python programming focusing on lists and tuples, detailing their definitions, differences, and various operations. It includes multiple Python programs demonstrating how to manipulate lists, such as finding the largest element, reversing a list, and counting occurrences of elements. Additionally, it covers creating lists based on user input and filtering elements based on divisibility.

Uploaded by

Gaikwad Nikhil
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)
23 views

Assignment 2

The document is an assignment on Python programming focusing on lists and tuples, detailing their definitions, differences, and various operations. It includes multiple Python programs demonstrating how to manipulate lists, such as finding the largest element, reversing a list, and counting occurrences of elements. Additionally, it covers creating lists based on user input and filtering elements based on divisibility.

Uploaded by

Gaikwad Nikhil
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/ 26

Assignment - 2

Topics: List, tuple


Roll No. : 027

Name: Kiran Ganesh Tayde

Assignment date: 28/04/2022

1. What is a List?

Ans:

1 list is a collection of items/multiple data types, enclosed by sqaure brackets []


2 It is a sequence data type in Python that is a mutable, or changeable, ordered
sequence of elements.

2. What is a Tuple?

Ans:

1 list is a collection of items/multiple data types, enclosed in a paranthessis ()


2 It is a sequence data type in Python that is a immutable, or unchangeable,
ordered sequence of elements.

3. What is the difference between List and Tuple?

Ans:

1 list data type tuple data type


2
3 1. mutable data type 1. immutable data type
4 2. enclosed by square brackets [] 2. enclosed by paranthessis ()
5 3. variable length 3. fixed length
6 4. more functional 4. less functional
7 5. requires more memory space 5. requires less memory space than list
8 6. slower than tuple 6. tuples are faster than lists
9

4. Python Program to find the largest element in the list

Ans:
In [1]:

1 l1=[12,45,32,85,15]
2 max1 = 0
3 for i in l1:
4 if i > max1:
5 max1 = i
6 else:
7 pass
8 print("Largest element in list >>>",max1)

Largest element in list >>> 85

In [2]:

1 l1=[12,45,32,85,15]
2 l1.sort()
3 print("Largest element >>",l1[-1])

Largest element >> 85

5. Python program to interchange first and last elements in a list.

Ans:

In [3]:

1 list1=["python",98,22,[10,30],"data",100]
2 print("Original list is: ",list1)
3
4 list1[0], list1[-1] = list1[-1], list1[0]
5
6 print("Updated list is : ",list1)

Original list is: ['python', 98, 22, [10, 30], 'data', 100]
Updated list is : [100, 98, 22, [10, 30], 'data', 'python']

6. Python program to swap two elements in a list.

Ans:

In [4]:

1 list2= [23,63,45,78,96]
2 print("Original list is: ",list2)
3
4 # We are swaping 1st index item with 3rd index item
5
6 list2[1], list2[3] = list2[3], list2[1]
7
8 print("Updated list is : ",list2)

Original list is: [23, 63, 45, 78, 96]


Updated list is : [23, 78, 45, 63, 96]
7. Python program to Reverse a List.

Ans:

In [16]:

1 l1 = [1,2,3,4,5,6]
2 l2 = l1[::-1]
3 l2

Out[16]:

[6, 5, 4, 3, 2, 1]

In [6]:

1 l1 = [10,63,1.556,96,"python",45.63,"machine learning","data science"]


2 print("Original list is:", l1)
3 l1.reverse()
4
5 print("Reversed list is:",l1)

Original list is: [10, 63, 1.556, 96, 'python', 45.63, 'machine learning',
'data science']
Reversed list is: ['data science', 'machine learning', 45.63, 'python', 9
6, 1.556, 63, 10]

In [5]:

1 l1 = [10,63,1.556,96,"python",45.63,"machine learning","data science"]


2 print("Original list is:", l1)
3 l2 = l1[::-1]
4
5 print("Reversed list is:",l2)

Original list is: [10, 63, 1.556, 96, 'python', 45.63, 'machine learning',
'data science']
Reversed list is: ['data science', 'machine learning', 45.63, 'python', 9
6, 1.556, 63, 10]

8. Python program to count occurrences of an element in a list.

Ans:
In [7]:

1 l1= [2,3,2,2,4,5,3]
2
3 for i in set(l1):
4 print(f"{i} occurs {l1.count(i)} times in list")

2 occurs 3 times in list


3 occurs 2 times in list
4 occurs 1 times in list
5 occurs 1 times in list

In [19]:

1 l1= [2,3,2,2,4,5,3]
2 ele = int(input("Enter an element :"))
3 print(f"{ele} occurs {l1.count(ele)} times in list")

Enter an element :2
2 occurs 3 times in list

9. Python program to find the sum of elements in a list

Ans:

In [8]:

1 l1 = [1,2,3,4,5]
2 s = 0
3 for i in l1:
4 s = s+i
5 print("sum of all element in a list :", s)

sum of all element in a list : 15

10.Python program to Multiply all numbers in the list

Ans:

In [9]:

1 l1 =[ 1,2,3,4,5,6]
2 m = 1
3 for i in l1:
4 m=m*i
5 print("Multiplication of all elements :",m)

Multiplication of all elements : 720

11. What are the ways to find the length of a list

Ans:
1 Method1: you can find it by using len() function

In [12]:

1 list1 = [10,30,12,63,"python","science"]
2 print("length of given list is :",len(list1))

length of given list is : 6

1 Method2:by using for loop

In [13]:

1 l1 = [10,30,12,63,"python","science"]
2 l = 0
3 for i in l1:
4 l=l+1
5 print("length of given list is :",l)

length of given list is : 6

12. WAP to find the smallest and largest number in a list (Without min-max
function)

Ans:

In [14]:

1 l1 = [10,96,5,44,52]
2 for i in range(len(l1)):
3 for j in range(i+1,len(l1)):
4 if l1[i] < l1[j]:
5 l1[i],l1[j] = l1[j],l1[i]
6
7 print("sorted list :",l1)
8 print("maximum value :",l1[0])
9 print("minimum value :",l1[-1])

sorted list : [96, 52, 44, 10, 5]


maximum value : 96
minimum value : 5

13. Python Program to find the area of a circle

Ans:
In [42]:

1 r = int(input("Enter radius :"))


2 a = 3.14 * r**2
3 print("Area of a circle is:", a)

Enter radius :10


Area of a circle is: 314.0

14. Take inputs from the user to make a list. Again take one input from the user
and search it in the list and delete that element, if found. Iterate over a list
using for loop

Ans:

In [84]:

1 list1=[]
2
3 a=int(input("enter length of list:"))
4 for i in range (a):
5 list1.append(int(input("enter elements of list:")))
6 print("list given by user :",list1)
7
8 f = int(input("enter element you want to search:"))
9 for item in list1:
10 if item == f:
11 list1.remove(item)
12 print("list after removing element is:",list1)
13 break
14 else :
15 print("element not found")
16

enter length of list:3


enter elements of list:56
enter elements of list:45
enter elements of list:12
list given by user : [56, 45, 12]
enter element you want to search:12
list after removing element is: [56, 45]
In [97]:

1 list1=[]
2
3 a=int(input("enter length of list:"))
4 for i in range (a):
5 list1.append(int(input("enter elements of list:")))
6 print("list given by user :",list1)
7
8 f = int(input("enter element you want to search:"))
9 for item in list1:
10 if item == f:
11 list1.remove(item)
12 print("list after removing element is:",list1)
13 break
14 else :
15 print("element not found")
16

enter length of list:4


enter elements of list:12
enter elements of list:45
enter elements of list:89
enter elements of list:100
list given by user : [12, 45, 89, 100]
enter element you want to search:50
element not found

15. You are given a list of integer elements. Make a new list that will store a
square of elements of the previous list. (With and without list
comprehension)

i. Input_list = [2,5,6,12]

ii. Output_list = [4,25,36,144]

Ans:

In [2]:

1 Input_list = [2,5,6,12]
2 print("Input list :",Input_list)
3
4 sq_list =[i**2 for i in Input_list]
5 print("Output list :",sq_list)

Input list : [2, 5, 6, 12]


Output list : [4, 25, 36, 144]

16. WAP to create two lists, one containing all even numbers and the other
containing all odd numbers between 0 to 151

Ans:
In [3]:

1 even = [i for i in range(0,152) if i%2==0]


2 odd = [i for i in range(0,152) if i%2!=0]
3 print("Even numbers>>",even)
4 print("*"*90)
5 print("Odd numbers>>",odd)

Even numbers>> [0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30,
32, 34, 36, 38, 40, 42, 44, 46, 48, 50, 52, 54, 56, 58, 60, 62, 64, 66, 6
8, 70, 72, 74, 76, 78, 80, 82, 84, 86, 88, 90, 92, 94, 96, 98, 100, 102, 1
04, 106, 108, 110, 112, 114, 116, 118, 120, 122, 124, 126, 128, 130, 132,
134, 136, 138, 140, 142, 144, 146, 148, 150]
**************************************************************************
****************
Odd numbers>> [1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, 27, 29, 31,
33, 35, 37, 39, 41, 43, 45, 47, 49, 51, 53, 55, 57, 59, 61, 63, 65, 67, 6
9, 71, 73, 75, 77, 79, 81, 83, 85, 87, 89, 91, 93, 95, 97, 99, 101, 103, 1
05, 107, 109, 111, 113, 115, 117, 119, 121, 123, 125, 127, 129, 131, 133,
135, 137, 139, 141, 143, 145, 147, 149, 151]

17. Python program to Count Even and Odd numbers in a List

Ans:

In [35]:

1 l1=[11,20,41,52,66,96,78,200]
2 even = [i for i in l1 if i%2==0]
3 odd = [i for i in l1 if i%2!=0]
4 print("Count of even numbers >>",len(even))
5 print("Count of odd numbers >>",len(odd))

Count of even numbers >> 6


Count of odd numbers >> 2

18. WAP to make new lists, containing only numbers which are divisible by 4, 6,
8, 10, 3, 5, 7, and 9 in separate lists for range(0,151)

Ans:
In [44]:

1 four = [i for i in range(0,152) if i%4 == 0]


2 five = [i for i in range(0,152) if i%5 == 0]
3 six = [i for i in range(0,152) if i%6 == 0]
4 eight = [i for i in range(0,152) if i%8 == 0]
5 ten = [i for i in range(0,152) if i%10 == 0]
6 three = [i for i in range(0,152) if i%3 == 0]
7 seven = [i for i in range(0,152) if i%7 == 0]
8 nine = [i for i in range(0,152) if i%9 == 0]
9 print("list containing only elements divisible by 4 is :",four)
10 print("*"*74)
11 print("list containing only elements divisible by 6 is :",six)
12 print("*"*74)
13 print("list containing only elements divisible by 8 is :",eight)
14 print("*"*74)
15 print("list containing only elements divisible by 10 is :",ten)
16 print("*"*74)
17 print("list containing only elements divisible by 3 is :",three)
18 print("*"*74)
19 print("list containing only elements divisible by 5 is :",five)
20 print("*"*74)
21 print("list containing only elements divisible by 7 is :",seven)
22 print("*"*74)
23 print("list containing only elements divisible by 9 is :",nine)
24
25

list containing only elements divisible by 4 is : [0, 4, 8, 12, 16, 20, 2


4, 28, 32, 36, 40, 44, 48, 52, 56, 60, 64, 68, 72, 76, 80, 84, 88, 92, 96,
100, 104, 108, 112, 116, 120, 124, 128, 132, 136, 140, 144, 148]
**************************************************************************
list containing only elements divisible by 6 is : [0, 6, 12, 18, 24, 30, 3
6, 42, 48, 54, 60, 66, 72, 78, 84, 90, 96, 102, 108, 114, 120, 126, 132, 1
38, 144, 150]
**************************************************************************
list containing only elements divisible by 8 is : [0, 8, 16, 24, 32, 40, 4
8, 56, 64, 72, 80, 88, 96, 104, 112, 120, 128, 136, 144]
**************************************************************************
list containing only elements divisible by 10 is : [0, 10, 20, 30, 40, 50,
60, 70, 80, 90, 100, 110, 120, 130, 140, 150]
**************************************************************************
list containing only elements divisible by 3 is : [0, 3, 6, 9, 12, 15, 18,
21, 24, 27, 30, 33, 36, 39, 42, 45, 48, 51, 54, 57, 60, 63, 66, 69, 72, 7
5, 78, 81, 84, 87, 90, 93, 96, 99, 102, 105, 108, 111, 114, 117, 120, 123,
126, 129, 132, 135, 138, 141, 144, 147, 150]
**************************************************************************
list containing only elements divisible by 5 is : [0, 5, 10, 15, 20, 25, 3
0, 35, 40, 45, 50, 55, 60, 65, 70, 75, 80, 85, 90, 95, 100, 105, 110, 115,
120, 125, 130, 135, 140, 145, 150]
**************************************************************************
list containing only elements divisible by 7 is : [0, 7, 14, 21, 28, 35, 4
2, 49, 56, 63, 70, 77, 84, 91, 98, 105, 112, 119, 126, 133, 140, 147]
**************************************************************************
list containing only elements divisible by 9 is : [0, 9, 18, 27, 36, 45, 5
4, 63, 72, 81, 90, 99, 108, 117, 126, 135, 144]

19. From a list containing ints, strings, and floats, make three lists to store them
separately.

Ans:

In [4]:

1 l1 =[ "p",12,63,3.6,"y","t",6.9]
2 s = [i for i in l1 if type(i) == str]
3 i = [i for i in l1 if type(i) == int]
4 f = [i for i in l1 if type(i) == float]
5 print(f"List of int data types :",i)
6 print(f"List of float data types :",f)
7 print(f"List of string data types:",s)
8

List of int data types : [12, 63]


List of float data types : [3.6, 6.9]
List of string data types: ['p', 'y', 't']

In [5]:

1 list1=["python",12,6.9,9.66,"data_science",255,50,"fibonacci","data",45.6,98.2]
2 s_list=[]
3 f_list=[]
4 i_list=[]
5
6 for i in list1:
7 if type(i)==int:
8 i_list.append(i)
9 elif type(i)==float:
10 f_list.append(i)
11 else:
12 s_list.append(i)
13
14 print(f"List of int data types :",i_list)
15 print(f"List of float data types :",f_list)
16 print(f"List of string data types:",s_list)
17

List of int data types : [12, 255, 50]


List of float data types : [6.9, 9.66, 45.6, 98.2]
List of string data types: ['python', 'data_science', 'fibonacci', 'data']

20. What’s The Difference Between The Python append() and extend()
Methods?

Ans:

1 append():
2
3 1. This method will add only one item at a time in a existing list.
4 2. It doesnt return new list of items , but will modify original list by adding
new item at the end of list
5 3. after executing append function size of the list will be increased by 1
6 3. syntax: list1.append(item)
7
8 extend():
9
10 1. This method will add all the elements of iterable (list,tuple,string) to the
end of the list
11 2. we can use it to simply join two lists
12 3. syntax: list1.extend(iterable)

In [6]:

1 #Example of append()
2
3 l1=[20,30,63,89,45]
4 print("Original list is:",l1)
5
6 l1.append("python")
7 print("Updated list is :",l1)

Original list is: [20, 30, 63, 89, 45]


Updated list is : [20, 30, 63, 89, 45, 'python']

In [7]:

1 #Example of extend()
2
3 l1=[20,50,30,93]
4 print("items in list1 :",l1)
5
6 t1=(20,63,69)
7 print("items in tuple1:",t1)
8
9 l1.extend(t1)
10 print("Updated list is:",l1)

items in list1 : [20, 50, 30, 93]


items in tuple1: (20, 63, 69)
Updated list is: [20, 50, 30, 93, 20, 63, 69]

21. Write a Python program to append a list to the second list

Ans:
In [9]:

1 #logic 1: by using for loop and append() function


2
3 l1=[20,89,45,63,12,10]
4 l2=["python","data","science"]
5 print("list 1 is :",l1)
6 print("list 2 is :",l2)
7
8 #want to append l2 to l1
9
10 for char in l2:
11 l1.append(char)
12
13 print("Updated list is:",l1)
14

list 1 is : [20, 89, 45, 63, 12, 10]


list 2 is : ['python', 'data', 'science']
Updated list is: [20, 89, 45, 63, 12, 10, 'python', 'data', 'science']

In [8]:

1 #logic 2: by using extend function


2
3 l1=[20,89,45,63,12,10]
4 l2=["python","data","science"]
5 print("list 1 is :",l1)
6 print("list 2 is :",l2)
7
8 #want to append l2 to l1
9
10 l1.extend(l2)
11
12 print("Updated list is:",l1)
13

list 1 is : [20, 89, 45, 63, 12, 10]


list 2 is : ['python', 'data', 'science']
Updated list is: [20, 89, 45, 63, 12, 10, 'python', 'data', 'science']

22. Write a Python program to find the third-largest number in a list.

Ans:
In [47]:

1 l1 = [1,52,63,74,12,364,313,41]
2 for i in range(len(l1)):
3 for j in range(i+1,len(l1)):
4 if l1[i] < l1[j]:
5 l1[i] , l1[j] = l1[j] , l1[i]
6 print("sorted list >> ", l1)
7 print("third largest element >> ",l1[2])

sorted list >> [364, 313, 74, 63, 52, 41, 12, 1]
third largest element >> 74

23. Write a Python program to get the frequency of the elements in a list.

Ans:

In [65]:

1 l1 = [11,2,3,1,3,1,3,15,55,7,55]
2 l2 = []
3 for i in l1:
4 if i not in l2:
5 l2.append(i)
6 for i in l2:
7 print(f"{i} occurs {l1.count(i)} times ")

11 occurs 1 times
2 occurs 1 times
3 occurs 3 times
1 occurs 2 times
15 occurs 1 times
55 occurs 2 times
7 occurs 1 times

In [49]:

1 l1 = [11,2,3,1,3,1,3,15,55,7,55]
2 for i in set(l1):
3 print(f"{i} occurs {l1.count(i)} times")

1 occurs 2 times
2 occurs 1 times
3 occurs 3 times
7 occurs 1 times
11 occurs 1 times
15 occurs 1 times
55 occurs 2 times

24. Write a Python program to check whether a list contains a sublist.

Ans:
In [66]:

1 list1=[100,[200,30,50],"python","data"]
2 for i in list1:
3 if type(i)==list:
4 print("List contains Sublist")
5 break
6 else:
7 print("List does not contain sublist")

List contains Sublist

In [67]:

1 list1=[100,200,30,50,"python","data"]
2 for i in list1:
3 if type(i)==list:
4 print("List contains Sublist")
5 break
6 else:
7 print("List does not contain sublist")

List does not contain sublist

25. Write a Python program to generate all sublists of a list

Ans:

In [13]:

1 list1=[100,200,30,50,[10,20,30],[30,56]]
2 for i in list1:
3 if type(i) == list :
4 print("sublist >>>>",i)
5

sublist >>>> [10, 20, 30]


sublist >>>> [30, 56]

26. Write a Python program to find common items from two lists

Ans:
In [15]:

1 #logic1:
2
3
4 l1=[23,12,63,"python","data",[0,1],[5,1]]
5 l2=["python",22,[0,1,],20,63,"data",56,5.9]
6 c = []
7
8 for char in l1:
9 for val in l2:
10 if char == val:
11 c.append(char)
12 print("Common elements >>",c)

Common elements >> [63, 'python', 'data', [0, 1]]

27. How to flatten a list in python?

Ans:

1 >> flattening of lists means getting elements of sublists into a one-dimensional


list.
2 >> simply we can say converting nested list to simple one dimentional list
3 >> For example, a list [[1,2,3],[4,5,6]] is flattened into [1,2,3,4,5,6].

In [18]:

1 # Example
2
3 list1=[[10,20,30],["python",2.3,63.9],["data","science"]]
4
5 flatten_list =[]
6
7 for char in list1:
8 if type(char)==list:
9 for v in char:
10 flatten_list.append(v)
11 print(flatten_list)

[10, 20, 30, 'python', 2.3, 63.9, 'data', 'science']

28. How to sort a list in ascending and descending order without using the sort
function?

Ans:
In [16]:

1 l1= [10,25,74,52,41,96]
2 for i in range(len(l1)):
3 for j in range(i+1,len(l1)):
4 if l1[i] < l1[j]:
5 l1[i],l1[j]=l1[j],l1[i]
6 print("Descending order >>",l1)

Ascending order >> [96, 74, 52, 41, 25, 10]

In [17]:

1 l1= [10,25,74,52,41,96]
2 for i in range(len(l1)):
3 for j in range(i+1,len(l1)):
4 if l1[i] > l1[j]:
5 l1[i],l1[j]=l1[j],l1[i]
6 print("Ascending order >>",l1)

Descending order >> [10, 25, 41, 52, 74, 96]

29. How to sort a tuple?

Ans:

1 >> for sorting tuple , we have to first convert tuple into list.
2 >> then by using sort() function , we can sort list.
3 >> now we have to again convert our list into tuple
4 >> this way we can sort tuple

In [90]:

1 t1 = (12,41,10,63,96)
2 l1 = list(t1)
3 l1.sort()
4 t2 = tuple(l1)
5 t2

Out[90]:

(10, 12, 41, 63, 96)

In [91]:

1 t1 = (12,41,10,63,96)
2 t2 = tuple(sorted(t1))
3 t2

Out[91]:

(10, 12, 41, 63, 96)

30. Write a Python program to convert a list of multiple integers into a single
integer
a. [11, 33, 50] >>> 113350

Ans:

In [95]:

1 l1 = [11,33,50]
2 print("Input :",l1)
3 print("Output : ",end="")
4 for i in l1:
5 print(i,end="")

Input : [11, 33, 50]


Output : 113350

31. Difference between del and clear?

Ans:

1 clear()
2
3 >> it is list function
4 >> it used to delete all items from list and make a list empty
5 >> syntax: list1.clear()
6
7
8 del
9
10 >> it is a keyword
11 >> it is use to delete whole list or particular item from list by using its index
value
12
13

In [28]:

1 #Example of clear()
2
3 l1=[1,2,3,4,5,6,7]
4 l1.clear()
5 print(l1)

[]
In [31]:

1 #Example of del
2
3 l1=[1,2,3,4,5,6,7]
4 del l1
5 print(l1) # list is deleted, thats why it is showing this error

--------------------------------------------------------------------------
-
NameError Traceback (most recent call las
t)
~\AppData\Local\Temp/ipykernel_11644/3534540325.py in <module>
3 l1=[1,2,3,4,5,6,7]
4 del l1
----> 5 print(l1)

NameError: name 'l1' is not defined

32. Difference between remove and pop?

Ans:

1 remove()
2
3 >> it will remove first matching element from list
4 >> syntax: list1.remove(element)
5
6 pop()
7
8 >> it will removes item at given index from the list
9 >> syntax: list1.pop(index)

In [33]:

1 #example of remove()
2
3 l1=["mumbai","pune","hyderabad","banglore"]
4 print("Original list :", l1)
5
6 l1.remove("hyderabad")
7 print("After using remove function :",l1)
8

Original list : ['mumbai', 'pune', 'hyderabad', 'banglore']


After using remove function : ['mumbai', 'pune', 'banglore']
In [36]:

1 #example of pop()
2
3 l1=["mumbai","pune","hyderabad","banglore"]
4 print("Original list :", l1)
5
6 l1.pop(1)
7 print("After using pop function :",l1)
8

Original list : ['mumbai', 'pune', 'hyderabad', 'banglore']


After using pop function : ['mumbai', 'hyderabad', 'banglore']

33. Difference between indexing and Slicing?

Ans:

1 indexing:
2
3 >> indexing is used to access 1 item of particular index value from the given
list
4 >> syntax: list1[index]
5
6 slicing:
7
8 >> it is used to obtain a sublist from the given list by giving range of start
and end index value
9 >> syntax: list1[start_index (includig): end_index (excluding): step size]
10

In [45]:

1 # Example of indexing:
2
3 l1=[10,12,63,78,99,"python"]
4 index=5
5 a=l1[5]
6
7 print(" item:'{}' is present at an index :{} ".format(a,index))
8

item:'python' is present at an index :5


In [49]:

1 # Example of slicing:
2
3 l1=[10,12,63,78,99,"python"]
4
5 # suppose i want access char only from index value 1 to index value 4
6
7 b=l1[1:4+1]
8
9 print(" items from index value 1 to 4 includes:",b)

items from index value 1 to 4 includes: [12, 63, 78, 99]

34. Difference between sort and sorted?

Ans:

1 sort()
2
3 >> sort() is a list function, syntax: list1.sort()
4 >> by default it will sort list in ascending order.
5 >> if you want to sort in descending order , you can do that by changing default
value to (reverse=True)
6 >> but you cannot assign result to the new variable by using sort () function
7
8
9 sorted()
10
11 >> sorted() is built in function , syntax: var = sorted(list1)
12 >> you can assign result to new variable by using sorted() function
13

In [58]:

1 #by using sort()


2
3 l1=[12,63,7,8,96,45]
4 l1.sort()
5 print("ascending order :",l1)
6
7 l1.sort(reverse=True)
8 print("Descending order :",l1)
9

ascending order : [7, 8, 12, 45, 63, 96]


Descending order : [96, 63, 45, 12, 8, 7]
In [57]:

1 #by using sorted()


2
3 l1=[12,63,7,8,96,45]
4 l2=sorted(l1)
5 print("ascending order :",l2)
6
7 l3=sorted(l1,reverse=True)
8 print("Descending order :",l3)
9

ascending order : [7, 8, 12, 45, 63, 96]


Descending order : [96, 63, 45, 12, 8, 7]

35. Difference between reverse and reversed?

Ans:

1 reverse()
2
3 >> reverse() is a list function, syntax: list1.reverse()
4 >> it will convert list in reverse order.
5 >> but you cannot assign result to the new variable by using reverse() function
6
7
8 reversed()
9
10 >> reversed() is built in function , syntax: var = reversed(list1)
11 >> you can assign result to new variable by using reversed() function
12

In [59]:

1 #by using reverse()


2
3 l1= ["pune","mumbai","banglore","delhi"]
4 print("Original list:", l1)
5 l1.reverse()
6 print("Reverse list :", l1)

Original list: ['pune', 'mumbai', 'banglore', 'delhi']


Reverse list : ['delhi', 'banglore', 'mumbai', 'pune']

In [61]:

1 #by using reversed()


2
3 l1= ["pune","mumbai","banglore","delhi"]
4 print("Original list:", l1)
5 l2= list(reversed(l1))
6 print("Reverse list :", l2)

Original list: ['pune', 'mumbai', 'banglore', 'delhi']


Reverse list : ['delhi', 'banglore', 'mumbai', 'pune']
36. Difference between copy and deep copy?

Ans:

1 Difference between copy() and deep copy()


2
3 >> copy() create shallow copy of original object, whereas deepcopy() creates new
object of original object
4
5 >> if you change items in original list contaning int or float data type shallow
copy will not change
6
7 >> but if your list contains sublists and you have change items of sublist inside
original list, it will change items in shallow copy as well.
8
9 >> for that purpose we need buit in function called deep copy()
10
11 >> if your list contains sublists and you want change items of sublist inside
original list, it will still not change items in deep copy
12

In [76]:

1 #by using copy() method


2
3
4 l1=[10,20,[20,30]]
5 l2=l1.copy()
6 print("Orginal list :", l1)
7 print("copied list :", l2)
8
9 print("*"*50)
10 print("After assigning variable in original list")
11
12 l1[2][1]=100
13 print("Orginal list :", l1)
14 print("copied list :", l2)
15
16 print("Value has changed in both the lists")

Orginal list : [10, 20, [20, 30]]


copied list : [10, 20, [20, 30]]
**************************************************
After assigning variable in original list
Orginal list : [10, 20, [20, 100]]
copied list : [10, 20, [20, 100]]
Value has changed in both the lists
In [86]:

1 #by using deepcopy() method


2
3 import copy
4
5 a=[10,20,[20,30,90]]
6 b=copy.deepcopy(a)
7 print("Orginal list :", a)
8 print("copied list :", b)
9
10 print("*"*50)
11 print("After assigning variable in original list")
12
13 a[2][1]="data_science"
14 print("Orginal list :", a)
15 print("copied list :", b)
16
17 print("Value has not changed in deep copy list")

Orginal list : [10, 20, [20, 30, 90]]


copied list : [10, 20, [20, 30, 90]]
**************************************************
After assigning variable in original list
Orginal list : [10, 20, [20, 'data_science', 90]]
copied list : [10, 20, [20, 30, 90]]
Value has not changed in deep copy list

37. How to check whether the list is empty or not?

Ans:

In [62]:

1 l1 = [1,2,3,4,5]
2 if len(l1) == 0:
3 print("list is empty")
4 else:
5 print("list is not empty")

list is not empty

In [11]:

1 l1=[]
2
3 if l1 == []:
4 print(" list is empty")
5 else:
6 print("list is not empty")
7

list is empty

38. How to concatenate two lists?


Ans:

1 >> we can concatenate two lists by using extend function()

In [15]:

1 ## Example
2
3 l1=[10,20,30,40,50]
4 l2=[60,70,80,90,100]
5
6 l1.extend(l2)
7
8 print(l1)

[10, 20, 30, 40, 50, 60, 70, 80, 90, 100]

39. How to find the occurrences of an element in the python list?

Ans:

1 >> We can find occurances of elements in python in list by using count() function

In [77]:

1 list1=[10,20,63,120,20,89,20]
2 element=20
3 c=list1.count(element)
4
5 print("Occurances of 20 inside list1 is:",c)

Occurances of 20 inside list1 is: 3

40. How to flatten a list in python?

Ans:

1 >> flattening of lists means getting elements of sublists into a one-dimensional


list.
2 >> simply we can say converting nested list to simple one dimentional list
3 >> We can flatten list by using for loop and append() function
In [19]:

1 # Example
2
3 list1=[[10,20,30],["python",2.3,63.9],["data","science"]]
4
5 flatten_list =[]
6
7 for char in list1:
8 if type(char)==list:
9 for v in char:
10 flatten_list.append(v)
11 print(flatten_list)

[10, 20, 30, 'python', 2.3, 63.9, 'data', 'science']

Program for factorial

In [18]:

1 n = int(input("enter a number >> "))


2 fact = 1
3 if n >= 0:
4 for i in range(1,n+1):
5 fact = fact*i
6 print("factorial of given number is >>", fact)
7 else:
8 print("factorial does not exist")

enter a number >> 5


factorial of given number is >> 120

Program for Prime number

In [109]:

1 n = int(input("Enter a number :"))


2 for i in range(2,n):
3 if n%i==0:
4 print("It is not a prime number")
5 break
6 else:
7 print("It is a prime number")

Enter a number :7
It is a prime number

Program for fibbonacci series


In [19]:

1 n = int(input("Enter a number :"))


2 first =0
3 second =1
4 if n == 1:
5 print("Fibbonacci Series >>>>",first,end=" ")
6 elif n > 1:
7 print("Fibbonacci Series >>>>",first,second,end=" ")
8 for i in range(0,n-2):
9 new= first+second
10 print(new,end=" ")
11 first = second
12 second=new

Enter a number :8
Fibbonacci Series >>>> 0 1 1 2 3 5 8 13

You might also like