Lists in Python

Introduction

 
In this article, I will explain lists in Python.
 

Definition

 
A list is another type of object. They are used to store an indexed list of items. A list is a collection that is ordered and changeable. In Python lists are written with square brackets, and we use commas as symbols.
 
List In Python
 
Syntax
  1. demo= ["list 1""list 2",....]    
  2. print(demo)   
Sample program
  1. number = ["one""two""three"]#List so, we use square brackets    
  2. print(number)#list name     
Output
 
List In Python
 

Access items

 
The list is used to refer to the index number. Remember that the first position item is 0.
 
Example
  1. number = ["one""two""three"]    
  2. print(number[0])#0 position is first item    
Output
 
It will print the output screen to the first position item. Remember that the first position item is 0.
 
List In Python
 

Negative index

 
A negative index starts in the last position of the list. -1 is the last position of the list.
 
Example
  1. number = ["one""two""three"]    
  2. print(number[-1])#-1 position is last item.   
Output
 
It will print the output screen to the last position.
 
List In Python
 

Range of index

 
You can specify various indexes by means of specifying where to start and where to quit the range.
 
Syntax
  1. demo= ["list 1""list 2",....]    
  2. print(demo[start position: end position])     
Example
  1. number = ["one""two""three","four","five","six"]    
  2. print(number[1:4])    
  3. #It will print the output screen of the items from position 1 to 4.    
  4. #Remember that the first position item is 0.    
Output
 
It will print the output screen of the items from position 1 to 4.
 
List In Python
 

Change item value

 
Changing the value of a specific item refers to the index number.
 
Example
  1. number = ["one""two""three","four","five","six"]    
  2. number[2]="welcome"#Change 3 position values in “welcome”.    
  3. print(number)    
Output
 
Change 3 position values.
 
List In Python
 

Add items

 
The append () keyword is used to the add item in the last position.
 
Example
  1. number = ["one""two""three","four","five","six"]    
  2. number.append("welcome")#Adding the item in the last position is "welcome".    
  3. print(number)   
Output
 
Add the item in the last position.
 
List In Python
 

Remove items

 
The pop () keyword is used to remove the last position.
 
Example
  1. number = ["one""two""three","four","five","six"]    
  2. number.pop()#To remove the last position    
  3. print(number)   
Output
 
To remove the last position.
 
List In Python
 

Conclusion

 
In this article, we have seen a list in python. I hope this article was useful to you. Thanks for reading!


Similar Articles