0 votes
in Python by
Python List

1 Answer

0 votes
by
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[0],emp[1],emp[2]))  

print("printing departments...");  

print("Department 1:\nName: %s, ID: %d\nDepartment 2:\nName: %s, ID: %s"%(Dep1[0],Dep2[1],Dep2[0],Dep2[1]));  

print("HOD Details ....");  

print("CS HOD Name: %s, Id: %d"%(HOD_CS[1],HOD_CS[0]));  

print("IT HOD Name: %s, Id: %d"%(HOD_IT[1],HOD_IT[0]));  

print(type(emp),type(Dep1),type(Dep2),type(HOD_CS),type(HOD_IT));   

Output:

printing employee data...

Name : John, ID: 102, Country: USA

printing departments...

Department 1:

Name: CS, ID: 11

Department 2:

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.

Python Lists

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.

Related questions

0 votes
asked Feb 11, 2021 in Python by SakshiSharma
0 votes
asked May 17, 2020 in Python by sharadyadav1986
...