List in python is implemented to store the sequence of various type of data. However, python contains six data types that are capable to store the sequences but the most common and reliable type is list.
A list can be defined as a collection of values or items of different types. The items in the list are separated with the comma (,) and enclosed with the square brackets .
A list can be defined as follows.
L1 = ["John", 102, "USA"]
L2 = [1, 2, 3, 4, 5, 6]
L3 = [1, "Ryan"]
If we try to print the type of L1, L2, and L3 then it will come out to be a list.
Lets consider a proper example to define a list and printing its values.
emp = ["John", 102, "USA"]
Dep1 = ["CS",10];
Dep2 = ["IT",11];
HOD_CS = [10,"Mr. Holding"]
HOD_IT = [11, "Mr. Bewon"]
print("printing employee data...");
print("Name : %s, ID: %d, Country: %s"%(emp,emp,emp))
print("Department 1:\nName: %s, ID: %d\nDepartment 2:\nName: %s, ID: %s"%(Dep1,Dep2,Dep2,Dep2));
print("HOD Details ....");
print("CS HOD Name: %s, Id: %d"%(HOD_CS,HOD_CS));
print("IT HOD Name: %s, Id: %d"%(HOD_IT,HOD_IT));
printing employee data...
Name : John, ID: 102, Country: USA
Name: CS, ID: 11
Name: IT, ID: 11
HOD Details ....
CS HOD Name: Mr. Holding, Id: 10
IT HOD Name: Mr. Bewon, Id: 11
<class 'list'> <class 'list'> <class 'list'> <class 'list'> <class 'list'>
List indexing and splitting
The indexing are processed in the same way as it happens with the strings. The elements of the list can be accessed by using the slice operator .
The index starts from 0 and goes to length - 1. The first element of the list is stored at the 0th index, the second element of the list is stored at the 1st index, and so on.
Consider the following example.
Unlike other languages, python provides us the flexibility to use the negative indexing also. The negative indices are counted from the right. The last element (right most) of the list has the index -1, its adjacent left element is present at the index -2 and so on until the left most element is encountered.