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] Output: [12, 12, 36] |
count ( ) | Returns the number of similar elements present in the last. | List.count(value) | MyList=[36 ,12 ,12] Output: 2 |
index ( ) | Returns the index value of the first recurring element | List.index(element) | MyList=[36 ,12 ,12] Output: 0 |
reverse ( ) | Reverses the order of the element in the list. | List.reverse( ) | MyList=[36 ,23 ,12] 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] Output: 98 |
min( ) | Returns the minimum value in a list. | min(list) | MyList=[21,76,98,23] Output: 21 |
sum( ) | Returns the sum of values in a list. | sum(list) | MyList=[21,76,98,23] Output: 218 |
- [‘ab’, ‘cd’]
- [‘AB’, ‘CD’]
- [None, None]
- none of the mentioned
- 1 2 3 4
- 4 3 2 1
- error
- none of the mentioned
- 0 1 2 3
- 0 1 2 2
- 3 3 3 3
- error
- list1 = list()
- list1 = []
- list1 = list([1, 2, 3])
- all of the mentioned
- [‘h’, ‘e’, ‘l’, ‘l’, ‘o’]
- [‘hello’]
- [‘llo’]
- [‘olleh’]
- 5
- 4
- None
- Error
- 2445
- 133
- 12454
- 123
- 3
- 5
- 25
- 1
- 1
- 9
- 15
- Error
- list1.shuffle()
- shuffle(list1)
- random.shuffle(list1)
- random.shuffleList(list1)
- print(list1[0])
- print(list1[:2])
- print(list1[:-2])
- all of the mentioned
- Error
- None
- 25
- 2
- [2, 33, 222, 14]
- Error
- 25
- [25, 14, 222, 33, 2]
- A
- Daman
- Error
- n
- [2, 6, 4]
- [1, 3, 2, 1, 3]
- [1, 3, 2, 1, 3, 2]
- [1, 3, 2, 3, 2, 1]
- [0, 1, 2, 3]
- [0, 1, 2, 3, 4]
- [0.0, 0.5, 1.0, 1.5]
- [0.0, 0.5, 1.0, 1.5, 2.0]
- True
- False
- Error
- None
- list1.add(5)
- list1.append(5)
- list1.addLast(5)
- list1.addEnd(5)
- list1.insert(3, 5)
- list1.insert(2, 5)
- list1.add(3, 5)
- list1.append(3, 5)
- list1.remove(“hello”)
- list1.remove(hello)
- list1.removeAll(“hello”)
- list1.removeOne(“hello”)
- 0
- 1
- 4
- 2
- 0
- 4
- 1
- 2
- [3, 4, 5, 20, 5, 25, 1, 3]
- [1, 3, 3, 4, 5, 5, 20, 25]
- [25, 20, 5, 5, 4, 3, 3, 1]
- [3, 1, 25, 5, 20, 5, 4, 3]
- [3, 4, 5, 20, 5, 25, 1, 3, 34, 5]
- [1, 3, 3, 4, 5, 5, 20, 25, 34, 5]
- [25, 20, 5, 5, 4, 3, 3, 1, 34, 5]
- [1, 3, 4, 5, 20, 5, 25, 3, 34, 5]
- [3, 4, 5, 20, 5, 25, 1, 3]
- [1, 3, 3, 4, 5, 5, 20, 25]
- [3, 5, 20, 5, 25, 1, 3]
- [1, 3, 4, 5, 20, 5, 25]
- [3, 4, 5, 20, 5, 25, 1]
- [1, 3, 3, 4, 5, 5, 20, 25]
- [3, 5, 20, 5, 25, 1, 3]
- [1, 3, 4, 5, 20, 5, 25]
- [‘a’, ‘b’, ‘c’, ‘d’]
- [‘a b c d’]
- [‘a#b#c#d’]
- [‘abcd’]
- 1
- 2
- 3
- 4
- 2 3 4 5 6 1
- 6 1 2 3 4 5
- 2 3 4 5 6 6
- 1 1 2 3 4 5
- [1, 3]
- [4, 3]
- [1, 4]
- [1, 3, 4]
- [1, 44]
- [1, 2, 3, 44]
- [44, 2, 3]
- [1, 2, 3]
- Heeeo
- Heelo
- Heleo
- None
- s[]
- s.getitem(3)
- s.__getitem__(3)
- s.getItem(3)
- s.__len__()
- len(s)
- size(s)
- s.size()
- i.__add(j)
- i.__add__(j)
- i.__Add(j)
- i.__ADD(j)
- input(“Enter a string”)
- eval(input(“Enter a string”))
- enter(“Enter a string”)
- eval(enter(“Enter a string”))
- 3
- 5
- 6
- 33
- 1
- 3
- 5
- 6
- The program prints two rows 3 4 5 1 followed by 33 6 1 2
- The program prints on row 3 4 5 1 33 6 1 2
- The program prints two rows 3 4 5 1 followed by 33 6 1 2
- The program prints two rows 1 3 4 5 followed by 1 2 6 33
- 1 2 3 4
- 4 5 6 7
- 1 3 8 12
- 2 5 9 13
- 3 33
- 1 1
- 5 6
- 5 33
- 1
- 2
- 4
- 5
- [[1, 2], [3, 1.5], [0.5, 0.5]]
- [[3, 1.5], [1, 2], [0.5, 0.5]]
- [[0.5, 0.5], [1, 2], [3, 1.5]]
- [[0.5, 0.5], [3, 1.5], [1, 2]]
- [10,34,56,[95]]
- [10,23,56,[78]]
- [10,23,56,[95]]
- [10,34,56,[78]]
- [3, 7, 8, 6, 1, 2]
- Syntax error
- [3,[7,8],6,1,2]
- [3,4,6,7,8]
- [1,2,3,4] [1,2,3,4]
- [1, 2, 3, 4] None
- Syntax error
- [1,2,3] [1,2,3,4]
- [13, 56, 17, [87], 45, 67]
- [13, 56, 17, 87, 45, 67]
- [13, 56, 17, 87,[ 45, 67]]
- [13, 56, 17, [87], [45, 67]]
- True True
- False True
- False False
- True False
- [‘Bangalore’, ‘Pune’, ‘Hyderabad’]
- [‘Bangalore’, ‘Pune’, ‘Delhi’]
- [‘Bangalore’, ‘Mumbai’, ‘Delhi’]
- [‘Bangalore’, ‘Mumbai’, ‘Hyderabad’]
- 5 5 1 2 3
- 5 1 2 3 4
- 2 3 4 5 1
- 2 3 4 5 5
- [‘Apple’, ‘Ball’, ‘Cobra’]
- [‘Ball’, ‘Apple’, ‘Cobra’]
- [‘Cobra’, ‘Apple’, ‘Ball’]
- Invalid syntax for sort()
- arr[-2]
- arr[2]
- arr[-1]
- arr[1]
- 0,1,2,3
- [0,1,2,3]
- range(0, 4)
- (0,1,2,3)
- list=()
- list.null
- null.list
- list=[]
- [3, 4, 5, 20, 5, 25, 1, 3]
- [1, 3, 3, 4, 5, 5, 20, 25]
- [3, 5, 20, 5, 25, 1, 3]
- [1, 3, 4, 5, 20, 5, 25]
- ['', 'b', 'bb', 'bbb']
- ['b,'bb', "bbb', "bbbb']
- ['b','bb', bbb']
- none of these
- [1, 4]
- [1,3, 4]
- [4,3]
- [1,3]
- list1.sum(5)
- list1.add(5)
- listl.append(5)
- list1.addelement(5)
- list1.addEnd (5)
- list1.addLast (5)
- list1.append (5)
- list1.add(5)
- 0
- 4
- 1
- 2
- list1.remove("hello")
- list1.remove(hello)
- list1.removeAll("hello")
- list1.removeOne ("hello")
- ['llo']
- ['hello']
- ['h', 'e', T', '1', 'o']
- None of the above
- arr[-2]
- arr[2]
- arr[-1]
- arr[1]
- pop()
- delete()
- remove_last()
- delete_last()
- 2
- 33
- 14
- 25
- list.contains(value)
- list.index(value)
- list.contains(value)
- value in list
- ValueError: attempt to assign sequence of size 6 to extended slice of size 5
- [10, 2, 20, 4, 30, 6, 40, 8, 50, 60]
- [1, 2, 10, 20, 30, 40, 50, 60]
- [1, 10, 3, 20, 5, 30, 7, 40, 9, 50, 60]
- fruit.shuffle()
- shuffle(fruit)
- random.shuffle(fruit)
- random.shuffleList(fruit)
- Error
- None
- abcd
- [‘a’,’b’,’c’,’d’]
- . List is mutable & Tuple is immutable
- List is immutable & Tuple is mutable
- Both are mutable
- Both are immutable