In this tutorial we will study the List Concept in Python.
List in python is a sequence or collection of elements. Unlike arrays in C programming language, lists in python differ in three ways.
Difference between the list in python and array in C Programming language.
1. List in python can have heterogeneous elements.
2. Array supports both direct and sequential access. List supports on direct access.
3. List can have list as a element.
An empty list can be defined using list() function or empty square brackets.
list1 = list() OR list1 = 
Both will create an empty list.
The following example creates a list with three elements of the same type, and prints the elements of a list using the print function.
list1 = list(10, 20, 30) print (list1)
Output of the program is: [10, 20, 30]
In the following example, we will understand how to create a list with three elements of heterogeneous type. Here two elements are of type integer, two strings and one element is of double type.
list1 = list(10, 'Raj', 30, 'Sachin', 10.20) print(list1)
Like C, Python stores the elements of the list at numeric indices. You can use indexing operator to access the elements of a list in python. Next example shows how to access the list elements using the index operator.
l1 = [10, 20, 30] print (l1) print (l1)
Now, we will see how to create and display the list with nested elements.
l1 = ['spam', 5, [10, ['a', 20]], 'India'] print (l1) print (l1) print (l1) print (l1) print (l1) print (l1) print (l1)
In the above program we have created list “l1” with 4 elements. Then we have shown how to access and display the individual elements using index operator.
spam 5 [10, ['a', 20]] India 10 a 20
Next example shows how to modify the list elements.
l1 = [10, 20, 30] print ("Before Modificaton:", l1) l1 = 50 l1 = 60 l1 = 80 #l1[0:3] = [50, 60, 80] print ("After Modificaton:", l1)
This program creates a list with three elements and displays the original elements of the list. Then, modifies the list elements. Finally, the program displays the modified elements a list.
Before Modificaton: [10, 20, 30] After Modificaton: [50, 60, 80]
The presence of an element in a list is verified using in operator. If element is present then “in” operator return true otherwise false.
l1 = [10, 20, 30] 10 in l1 l1 = [10, 20, 30] 40 in l1
First one returns true as 10 is present in l1 and second returns false 40 is not present in l1.
Summary of List Concept in Python:
In this tutorial we have discussed, the definition of a list, how list differs from an array in C. Also we have seen how to create, display entire list and individual elements of a list using index operator. Finally, we, have seen list modification and “in” operator.
If you like the video, please share with your friends and if you have any query please let me know in the comment box.