List in Python

List in Python


A list in Python is known as a “sequence data type” like strings. It is an ordered collection of values enclosed within square brackets [ ]. Each value of a list is called as element. It can be of any type such as numbers, characters, strings and even the nested lists as well. Th e elements can be modifi ed or mutable which means the elements can be replaced, added or removed. Every element rests at some position in the list. Th e position of an element is indexed with numbers beginning with zero which is used to locate and access a particular element.


Create a List in Python

In python, a list is simply created by using square bracket. Th e elements of list should be specifi ed within square brackets. Th e following syntax explains the creation of list.

Syntax:

Variable = [element-1, element-2, element-3 …… element-n]

Example

Marks = [10, 23, 41, 75]
Fruits = [“Apple”, “Orange”, “Mango”, “Banana”]
MyList = [ ]

In the above example, the list Marks has four integer elements; second list Fruits has four string elements; third is an empty list. The elements of a list need not be homogenous type of data. The following list contains multiple type elements.

Mylist = [ “Welcome”, 3.14, 10, [2, 4, 6] ]

In the above example, Mylist contains another list as an element. This type of list is known as “Nested List”. 

Nested list is a list containing another list as an element.


Accessing List elements

Python assigns an automatic index value for each element of a list begins with zero. Index value can be used to access an element in a list. In python, index value is an integer number which can be positive or negative.

Positive value of index counts from the beginning of the list and negative value means counting backward from end of the list (i.e. in reverse order).

To access an element from a list, write the name of the list, followed by the index of the element enclosed within square brackets.

Syntax:

List_Variable = [E1, E2, E3 …… En]
print (List_Variable[index of a element])

Example (Accessing single element):

>>> Marks = [10, 23, 41, 75]
>>> print (Marks[0])
10

In the above example, print command prints 10 as output, as the index of 10 is zero.

Example: Accessing elements in revevrse order

>>> Marks = [10, 23, 41, 75]
>>> print (Marks[-1])
75

* A negative index can be used to access an element in reverse order.


(i) Accessing all elements of a list

Loops are used to access all elements from a list. The initial value of the loop must be zero. Zero is the beginning index value of a list.

Example

Marks = [10, 23, 41, 75]
i = 0
while i < 4:
print (Marks[i])
i = i + 1

Output

10
23
41
75

(ii) Reverse Indexing

Python enables reverse or negative indexing for the list elements. Thus, python lists index in opposite order. The python sets -1 as the index value for the last element in list and -2 for the preceding element and so on. This is called as Reverse Indexing.

Example

Marks = [10, 23, 41, 75]
i = -1
while i >= -4:
print (Marks[i])
i = i + -1

Output

75
41
23
10

List Length

The len( ) function in Python is used to find the length of a list. (i.e., the number of elements in a list). Usually, the len( ) function is used to set the upper limit in a loop to read all the elements of a list. If a list contains another list as an element, len( ) returns that inner list as a single element.

Example :Accessing single element

>>> MySubject = [“Tamil”, “English”, “Comp. Science”, “Maths”]
>>> len(MySubject)
4

Example : Program to display elements in a list using loop

MySubject = ["Tamil", "English", "Comp. Science", "Maths"]
i = 0
while i < len(MySubject):
print (MySubject[i])
i = i + 1

Output

Tamil
English
Comp. Science
Maths


Accessing elements using for loop

In Python, the for loop is used to access all the elements in a list one by one. This is just like the for keyword in other programming language such as C++.

Syntax:

for index_var in list:
print (index_var)

Here, index_var represents the index value of each element in the list. Python reads this “for” statement like English: “For (every) element in (the list of) list and print (the name of the) list items”

Example

Marks=[23, 45, 67, 78, 98]
for x in Marks:
print( x )

Output

23
45
67
78
98

In the above example, Marks list has 5 elements; each element is indexed from 0 to 4. The Python reads the for loop and print statements like English: “For (every) element (represented as x) in (the list of) Marks and print (the values of the) elements”.

Changing list elements

In Python, the lists are mutable, which means they can be changed. A list element or range of elements can be changed or altered by using simple assignment operator (=).

Syntax:

List_Variable [index of an element] = Value to be changed
List_Variable [index from : index to] = Values to changed

Where, index from is the beginning index of the range; index to is the upper limit of the range which is excluded in the range. For example, if you set the range [0:5] means, Python takes only 0 to 4 as element index. Thus, if you want to update the range of elements from 1 to 4, it should be specified as [1:5].

Example : Python program to update/change single value

MyList = [2, 4, 5, 8, 10]
print ("MyList elements before update... ")
for x in MyList:
print (x)
MyList[2] = 6
print ("MyList elements after updation... ")
for y in MyList:
print (y)

Output:

MyList elements before update...
2
4
5
8
10
MyList elements after updation...
2
4
6
8
10


Example : Python program to update/change range of values

MyList = [1, 3, 5, 7, 9]
print ("List Odd numbers... ")
for x in MyList:
print (x)
MyList[0:5] = 2,4,6,8,10
print ("List Even numbers... ")
for y in MyList:
print (y)

Output

List Odd numbers...
1
3
5
7
9
List Even numbers...
2
4
6
8
10


Adding more elements in a list

In Python, append( ) function is used to add a single element and extend( ) function is used to add more than one element to an existing list.

Syntax:

List.append (element to be added)
List.extend ( [elements to be added])

In extend( ) function, multiple elements should be specified within square bracket as arguments of the function.

Example

>>> Mylist=[34, 45, 48]
>>> Mylist.append(90)
>>> print(Mylist)
[34, 45, 48, 90]

In the above example, Mylist is created with three elements. Through >>> Mylist.append(90) statement, an additional value 90 is included with the existing list as last element, following print statement shows all the elements within the list MyList.

Example

>>> Mylist.extend([71, 32, 29])
>>> print(Mylist)
[34, 45, 48, 90, 71, 32, 29]

In the above code, extend( ) function is used to include multiple elements, the print statement shows all the elements of the list after the inclusion of additional elements.


Inserting elements in a list

As you learnt already, append( ) function in Python is used to add more elements in a list. But, it includes elements at the end of a list. If you want to include an element at your desired position, you can

use insert ( ) function. The insert( ) function is used to insert an element at any position of a list.

Syntax:

List.insert (position index, element)

Example

>>> MyList=[34,98,47,'Kannan', 'Gowrisankar', 'Lenin', 'Sreenivasan' ]
>>> print(MyList)
[34, 98, 47, 'Kannan', 'Gowrisankar', 'Lenin', 'Sreenivasan']
>>> MyList.insert(3, 'Ramakrishnan')
>>> print(MyList)
[34, 98, 47, 'Ramakrishnan', 'Kannan', 'Gowrisankar', 'Lenin', 'Sreenivasan']

In the above example, insert( ) function inserts a new element ‘Ramakrishnan’ at the index value 3, ie. at the 4th position. While inserting a new element in between the existing elements, at a particular location, the existing elements shifts one position to the right.

Deleting elements from a list

There are two ways to delete an element from a list viz. del statement and remove( ) function. del statement is used to delete known elements whereas remove( ) function is used to delete elements of a list if its index is unknown. The del statement can also be used to delete entire list.

Syntax:

del List [index of an element]
# to delete a particular element
del List [index from : index to]
# to delete multiple elements
del List
# to delete entire list

Example

>>> MySubjects = ['Tamil', 'Hindi', 'Telugu', 'Maths']
>>> print (MySubjects)
['Tamil', 'Hindi', 'Telugu', 'Maths']
>>> del MySubjects[1]
>>> print (MySubjects)
['Tamil', 'Telugu', 'Maths']

In the above example, the list MySubjects has been created with four elements. print statement shows all the elements of the list. In >>> del MySubjects[1] statement, deletes an element whose index value is 1 and the following print shows the remaining elements of the list.

Example

>>> del MySubjects[1:3]
>>> print(MySubjects)
['Tamil']

In the above codes, >>> del MySubjects[1:3] deletes the second and third elements from the list. The upper limit of index is specified within square brackets, will be taken as -1 by the python.

Example

>>> del MySubjects
>>> print(MySubjects)
Traceback (most recent call last):
File "<pyshell#9>", line 1, in <module>
print(MySubjects)
NameError: name 'MySubjects' is not defined

List and range ( ) function

The range( ) is a function used to generate a series of values in Python. Using range( ) function, you can create list with series of values. The range( ) function has three arguments.

Syntax of range ( ) function:

range (start value, end value, step value)

where,

start value – beginning value of series. Zero is the default beginning value.

end value – upper limit of series. Python takes the ending value as upper limit – 1.

step value – It is an optional argument, which is used to generate different interval of values.

Example : Generating whole numbers upto 10

for x in range (1, 11):
print(x)

Output

1
2
3
4
5
6
7
8
9
10

Example : Generating first 10 even numbers

for x in range (2, 11, 2):
print(x)

Output

2
4
6
8
10

Creating a list with series of values

Using the range( ) function, you can create a list with series of values. To convert the result of range( ) function into list, we need one more function called list( ). The list( )

function makes the result of range( ) as a list.

Syntax:

List_Varibale = list ( range ( ) )

Example

>>> Even_List = list(range(2,11,2))
>>> print(Even_List)
[2, 4, 6, 8, 10]


Other important list funcion

Function
Description
Syntax
Example
copy ( )
Returns a copy of the list
List.copy( )

MyList=[12, 12, 36]
x = MyList.copy()
print(x)

Output:

[12, 12, 36]

count ( )
Returns the number of similar elements present in the last.
List.count(value)
MyList=[36 ,12 ,12]
x = MyList.count(12)
print(x)

Output:

2

index ( )
Returns the index value of the first recurring element
List.index(element)
MyList=[36 ,12 ,12]
x = MyList.index(12)
print(x)

Output:

0

reverse ( )
Reverses the order of the element in the list.
List.reverse( )
MyList=[36 ,23 ,12]
MyList.reverse()
print(MyList)

Output:

[12 ,23 ,36]

sort ( )
Sorts the element in list
List.sort(reverse=True|False, key=myFunc)

max( )
Returns the maximum value in a list.
max(list)
MyList=[21,76,98,23]
print(max(MyList))

Output:

98

min( )
Returns the minimum value in a list.
min(list)
MyList=[21,76,98,23]
print(min(MyList))

Output:

21

sum( )
Returns the sum of values in a list.
sum(list) 
MyList=[21,76,98,23]
print(sum(MyList))

Output:

218

Qus What do you understand by mutability?

Ans: Mutable means changeable. In Python, mutable types are those whose values can be changed in place. Only three types are mutable in python – Lists, Dictionaries and Sets.

Qus Start with the list[8,9,10]. Do the following using list functions

(a) Set the second entry (index 1) to 17

(b) Add 4, 5 and 6 to the end of the list.

(c) Remove the first entry from the list.

(d) Sort the list.

(e) Double the list.

(f) Insert 25 at index 3


Ans:

(a) list[1]=17

(b) list.append(4)

list.append(5)

list.append(6)

(c) list.pop(0)

(d) list.sort()

(e) list=list*2

(f) list.insert(3,25)


Qus.  If a is [1, 2, 3], what is the difference (if any) between a*3 and [a, a, a]?

Ans: a*3 will produce [1,2,3,1,2,3,1,2,3], means a list of integers and [a, a, a] will produce [[1,2,3],[1,2,3],[1,2,3]], means list of lists


Qus. If a is [1, 2, 3], is a *3 equivalent to a + a + a?

Ans: Yes, Both a*3 and a+a+a will produce same result.


Qus. If a is [1, 2, 3], what is the meaning of a [1:1] = 9?

Ans: This will generate an error "TypeError: can only assign an iterable'.


Qus If a is [1, 2, 3], what is the meaning of a [1:2] = 4 and a [1:1] = 4?

Ans: These will generate an error "TypeError: can only assign an iterable".

Qus. What are list slices?

Ans: List slices are the sub-part of a list extracted out. You can use indexes of the list elements to create list slices as per following format. Syntax is as follows –

Qus Does a slice operator always produce a new list?

Ans: Yes, this will create a new list.


Qus. How are lists different from strings when both are sequences?

Ans: Lists are similar to strings in many ways like indexing, slicing, and accessing individual elements but they are different in the sense that

(i) Lists are mutable while strings are immutable.

(ii) In consecutive locations, strings store the individual characters while list stores the references of its elements.

(iii) Strings store single type of elements-all characters while lists can store elements belonging to different types.


Qus. What are nested Lists?

Ans: A list can have an element in it, which itself is a list. Such a list is called nested list. e.g.

L = [1,2,3,4,[5,6,7],8]


Qus. Discuss the utility and significance of Lists.

Ans: The list is a most versatile datatype available in Python which can be written as a list of comma-separated values (items) between square brackets. Important thing about a list is that items in a list need not be of the same type. List is majorly used with dictionaries when there is large number of data.


Qus What is the purpose of the del operator and pop method? Try deleting a slice.

Ans: del operator is used to remove an individual item, or to remove all items identified by a slice. It is to be used as per syntax given below –

>>>del List[index]

>>>del List[start:stop]

pop method is used to remove single element, not list slices. The pop() method removes an individual item and returns it. Its syntax is –

>>>a=List.pop() #this will remove last item and deleted item will be assigned to a.

>>>a=List[10] # this will remove the ite at index 10 and deleted item will be assigned to a.


Qus. What are list slices?

Ans: List slices, like string slices are the sub part of a list extracted out. Indexes can be used to create list slices as per following format:

seq = L[start:stop]


Qus. What do you understand by true copy of a list? How is it different from shallow copy?

Ans: A shallow copy means constructing a new collection object and then populating it with references to the child objects found in the original. In essence, a shallow copy is only one level deep. The copying process does not recurse and therefore won‘t create copies of the child objects themselves.

True Copy means you can create a copy of a list using New_list=My_list. The assignment just copies the reference to the list, not the actual list, so both new_list and my_list refer to the same list after the assignment.


Qus What do you understand by immutability?

Ans: Immutability means not changeable. The immutable types are those that can never change their value in place. In python following types are immutable –

I. Integers

II. Floating point numbers

III. Booleans

IV. Strings

V. Tuples


Qus How are Tuples different from Lists when both are sequences?

Ans: Tuples are similar to lists in many ways like indexing, slicing, and accessing individual values but they are different in the sense that –

Tuples are immutable while lists are mutable.

List can grow or shrink while tuples cannot.


Qus Can tuples be nested?

Ans: Yes, tuples can be nested. e.g (1,2,3,(4,5,6))


Qus. Discuss the utility and significance of Tuples.

Ans: Tuples are great for holding static data that you don't plan on modifying and changing a lot. Tuples are four to seven times faster than lists. This means for every list item manipulated, four to seven tuples could be manipulated within that time frame. This has huge advantages for scientific work, as this allows for speedy data reading.


Qus. How can you say that a tuple is an ordered list of objects?

Ans: A tuple is an ordered list of objects. This is evidenced by the fact that the objects can be accessed through the use of an ordinal index amd for a given index, same element is returned every time.


Qus. Why can‟t List can be used as keys?

Ans: List is mutable datatype. And Keys of dictionary must be immutable type. This is the region that list cannot be used as keys.


Qus. What type of objects can be used as keys in dictionary?

Ans: Any immutable objects can be used as keys in dictionary.


Qus. Can you change the order of the dictionaries contents?

Ans: Yes, the order of dictionary contents may be changed.


Qus. Can you modify the keys in a dictionary?

Ans: Keys cannot be modified in dictionary while values are mutable in dictionary.


Qus. Can you modify the value in a dictionary?

Ans: Yes, Values can be modified in dictionaries.


Qus. Is dictionary Mutable? Why?

Ans: Dictionary is mutable type because we can change its values.


Qus How are dictionaries different from Lists?

Ans: The dictionary is similar to lists in the sense that it is also a collection of data-items but it is different from lists in the sense that lists are sequential collections(ordered) and dictionaries are non-sequential collections(unordered).

Elements in lists or tuples can be accessed by using indexes. But in dictionaries the values can be obtained using keys. By changing the sequence of key we can shuffle the order of elements of dictionary while this thing is not possible in list.


Qus. When are dictionaries more useful than lists?

Ans: Dictionaries can be much more useful than lists when we wanted to store all our friends cell-phone numbers. We could create a list of pairs,(name of friend, phone number), but once this list becomes long enough searching this list for a specific phone number will get-time consuming. Better would be if we could index the list by our friend‘s name. This is precisely what a dictionary does.


Qus. Discuss the utility and significance of Dictionaries.

Ans: Dictionaries can be much more useful than lists when we wanted to store all our friends cell-phone numbers. We could create a list of pairs,(name of friend, phone number), but once this list becomes long enough searching this list for a specific phone number will get-time consuming. Better would be if we could index the list by our friend‘s name. This is precisely what a dictionary does.


Qus. Why is a dictionary termed as an unordered collection of objects?

Ans: But in dictionaries the values can be obtained using keys. By changing the sequence of key we can shuffle the order of elements of dictionary while this thing is not possible in list. In dictionaries there is no index. It uses its keys as index which can be rearranged. That‘s why a dictionary termed as an unordered collection of objects


Qus. How is clear() function different from del <dict> Statement?

Ans: clear() removes all the elements of a dictionary and makes it empty dictionary while del statement removes the complete dictionary as an object. After del statement with a dictionary name, that dictionary object no longer exists, not even empty dictionary.


Programs

WAP to find the 2nd largest number from the list of the numbers entered through keyboard.


View Solution


Write a python program that creates a list of numbers from 1 to 20 that are divisible by 4


View Solution


Write a python program to define a list of countries that are a member of BRICS. Check whether a county is member of BRICS or not


View Solution


Python program to read marks of six subjects and to print the marks scored in each subject and show the total marks


View Solution


Python program to read prices of 5 items in a list and then display sum of all the prices, product of all the prices and find the average


View Solution


Python program to count the number of employees earning more than 1 lakh per annum. The monthly salaries of n number of employees are given


View Solution


Write a program to create a list of numbers in the range 1 to 10. Then delete all the even numbers from the list and print the final list.


View Solution


Write a program to generate in the Fibonacci series and store it in a list. Then find the sum of all values.


View Solution


Write a program to swap two values using tuple assignment


View Solution


Write a python program using a function that returns the area and circumference of a circle whose radius is passed as an argument.two values using tuple assignment


View Solution


Write a program that has a list of positive and negative numbers. Create a new tuple that has only positive numbers from the list


View Solution


Python Program that generate a set of prime numbers and another set of even numbers. Demonstrate the result of union, intersection, difference and symmetirc difference operations.


View Solution


WAP to find minimum element from a list of elements along with its index in the list.


View Solution


WAP to calculate mean of a given list of numbers.


View Solution


WAP to search for an element in a given list of numbers.


View Solution


WAP to count frequency of a given element in a list of numbers.


View Solution


WAP to calculate the sum of integers of the list


View Solution


WAP that reverses an array of integers (in place)


View Solution


WAP that creates a third list after adding two lists.


View Solution


WAP that repeatedly asks the user to enter product names and prices. Store all of them in a dictionary whose keys are product names and values are prices. And also write a code to search an item from the dictionary.


View Solution


WAP to create a dictionary named year whose keys are month names and values are their corresponding number of days.


View Solution


write  a program that input a list, replace it twice and then prints the sorted list in ascending and descending order.


View Solution


write a program to check if the maximum element of the list lies in the first half of the list or in the second half.


View Solution


write a program to input two lists and display the maximum elements from the elements of both the list combined, along with its index in its list.


View Solution


write a program to input a list of numbers and swap elements at the even location with the elements at the odd location.


View Solution


Write a program rotates the elements of a list so that the elements at the first index moves to the second index , the element in the second index moves to the third index, etc., and the element at the last index moves to the first index.


View Solution


Write a program to input ‘n’ numbers and store it in a tuple and find maximum & minimum values in the tuple.


View Solution


Write a program to input any two tuples and interchange the tuple values.


View Solution


Write a program to input any two tuples and interchange the tuple values.


View Solution


Write a python program to increment the elements of a list with a number.


View Solution


Ask the use to enter a list containing number between 1 and 12, then replace all the entries in the list that are  greater than 10 with 10


View Solution


Write a Python program that reverse a list of integers (in place)


View Solution


Write a python program that inputs two lists and creates a third, that contains all elements of the first followed by all elements of the second. 


View Solution


Ask the user to inter list of string. Create a new list that consist of those strings with their first characters removed.


View Solution


Write a Python program to Create a list using for loop which consist of integers 0 through 49


View Solution


Write a Python program to create a list using for loop which consist square of  the integers 1 through 50


View Solution


Write a Python program to create a list using for loop which consist ['a','bb','ccc','dddd',....] that ends with 26 copies of the letter z.


View Solution


Write a python program that takes any two list L and M of the same size and adds their elements together to from a new list N whose elements are sums of the corresponding elements in L and M. For instance, if L=[3,1,4] and M= [1,5,9] the N should equal [4,6,13].



View Solution


Write a python program to rotates the elements of a list so that the elements at the first index moves to the second index, the element in the second index moves to the third index, etc. and the elements in the last index moves to the first index.


View Solution


Write a python program to move all duplicate values in a list to the end of the list.


View Solution


Write a Python program display the maximum and minimum values form specified range of indexes of a list


View Solution


Write a python program to compare two equal sized list and print the first index where they differ


View Solution


Write a Python program to enter names of employees and their salaries as input and store them in a dictionary


View Solution


Write a program to count the number of times a character appears in a given string


View Solution


Write a program to convert a number entered by the user into its corresponding number in words.

For example, if the input is 876 then the output should be 'Eight Seven Six'.


View Solution


Repeatedly ask the user to enter a team name and how many games the team has won and how many they lost. Store this information in a dictionary where the keys are the team names and the values are a list of the form [wins, losses ].


(i) using the dictionary created above, allow the user to enter a team name and print out the team’s winning percentage.

(ii) using dictionary create a list whose entries are the number of wins for each team.

(iii) using the dictionary, create a list of all those teams that have winning records.


View Solution


Write a program that repeatedly asks the user to enter product names and prices. Store all of these  in a dictionary whose keys are the product names and whose values are the price .

When the user is done entering products and price, allow them to repeatedly enter a product name and print the corresponding price or a message if the product is not in dictionary.


View Solution


Create a dictionary whose keys are month name and whose values are number of days in the corresponding month:

(a) ask the user to enter the month name and use the dictionary to tell how many days are in month .

(b) print out all of the keys in alphabetical order  .

(c) print out all of the month with 31 days.

(d) print out the (key - value) pair sorted  by the number of the days in each month .


View Solution


Can you store the detail of 10 students in a dictionary at the same time? details include – rollno, name ,marks ,grade etc. Give example to support your answer.


View Solution


Given the dictionary x = {‘k1’: ‘v1’, ‘k2’ : ‘v2’, ‘k3’ : ‘v3’} ,create a dictionary with the opposite mapping.

Write a program to create the dictionary .


View Solution


Given two dictionaries say d1 and d2

Write a program that lists the over lapping keys of the two dictionaries if a key of d1 is also a key of d2 , the list it .


View Solution


Write a program that checks if two same values in a dictionary have different keys. 


View Solution


Write a program to check if a dictionary is contained in another dictionary.

 

e.g., if

 

d1 = {1:11, 2:12}

d2 = {1:11, 2:12, 3:13, 4:15}

 

Then d1 is contained in d2.


View Solution


A dictionary D1 has values in the form of lists of numbers. Write a program to create a new dictionary D2 having same keys as D1 but values as the sum of the list elements.

 

e.g.

 

D1 = {'A': [1, 2, 3], 'B': [4, 5, 6]}

Then

D2 is {'A':6, 'B': 15}


View Solution


A dictionary has three keys: 'assets', 'liabilities' and 'capital'. Each of these keys store their value in form of a list storing various values of 'assets', liabilities' and 'capital' respectively. Write a program to create a dictionary in this form and print. Also test if the accounting equation holds true.


View Solution


CCC Online Test 2021 CCC Practice Test Hindi Python Programming Tutorials Best Computer Training Institute in Prayagraj (Allahabad) Best Java Training Institute in Prayagraj (Allahabad) Best Python Training Institute in Prayagraj (Allahabad) O Level NIELIT Study material and Quiz Bank SSC Railway TET UPTET Question Bank career counselling in allahabad Sarkari Naukari Notification Best Website and Software Company in Allahabad Website development Company in Allahabad