A list is a sequence data type that includes collection of elements.
It is similar to an array.
List consist of group of elements or items
The only difference between array and list is that array store items or element of same data type whereas list store items of multiple data types
In the below example, array is use to represent student age. Age is an integer datatype
Array representing age of students = 10,12,9,13
List is created to represent student information. It contain name and address which are string datatype whereas age and mark represent integer datatype
List representing student details = name, age, address, marks
Lists are more versatile than array
Creating list
List can be created by embedding items or elements in a square braces []. Each element in a list is separated by comma
Syntax
list = [list1,list2….listn]
Example : Below is the student list which contain element of multiple datatype. It includes 2 integer and 2 string elements
student_info = [10,'Rohan','Mumbai',75]
Two of the most common operation performed on list are indexing and slicing.
Indexing represent position number of each element. The first element in the list is represented by index value 0, second element by 1 and so forth.
Below table represent index number and with their element
List Element | 10 | Rohan | Mumbai | 75 |
Index Number | 0 | 1 | 2 | 3 |
We can print each element from a list using its index number. To print ‘Mumbai’ use index number 2
student_info = [10,'Rohan','Mumbai',75]
print(student_info[2])
Output
Mumbai
Printing all elements of a list
student_info = [10,'Rohan','Mumbai',75]
print(student_info)
Output
[10, 'Rohan', 'Mumbai', 75]
Code : Create a list of cars and print the first and last element
Creating a list of cars
cars = ['Ferrari','Honda','Toyota','Renault']
Printing the first element using index number 0
print('First Element:',cars[0])
Now we can use len() to find the total number of elements inside a list
l = len(cars) print('Total number of items :',l)
Minus 1 from the total length to obtain the last element of the list
print('Last Element:',cars[l-1])
Output
First Element: Ferrari
Total number of items : 4
Last Element: Renault
Complete Code
cars = ['Ferrari','Honda','Toyota','Renault']
print('First Element:',cars[0])
l = len(cars)
print('Total number of items :',l)
print('Last Element:',cars[l-1])