Python Devlopment






Lists



2.5 Python Lists:

A list is a collection which is ordered and changeable. In Python lists are written with square brackets. Like array in other programming languages, first element of list is also start with zero.

Example:

 

fruits = ["Apple", "Mango", "Banana"]
print(fruits)

Output:    
[‘Apple’,’Mango’,’Banana’]

2.5.1 Accessing Elements:

   

fruits = ["Apple", "Mango", "Banana"]
print(fruits[1])

Output:    
Banana

2.5.2 Modifying Element Value:

  

fruits = ["Apple", "Mango", "Banana"]
fruits[1] = "Cherry"
print(fruits)

Output:    
[‘Apple’,’Cherry’,’Banana’]

2.5.3 Printing Complete List:

  

fruits = ["Apple", "Mango", "Banana"]
for x in fruits:          
    print(x)

Output:    
Apple    
Mango    
Banana

2.5.4 Checking presence of Element:

fruits = ["Apple", "Mango", "Banana"]
if "Apple" in fruits:          
    print("Yes, 'Apple' is in the fruits list")

2.5.5 Calculating Length of a List:

fruits = ["Apple", "Mango", "Banana"]
print(len(fruits))

Output:    
3

2.5.6 Adding Element:

To add an item to the end of the list, use the append() method:

fruits = ["Apple", "Mango", "Banana"]
fruits.append("Orange")    
print(fruits)

Output:    
[‘Apple’,’Mango’,’Banana’,’Orange’]

Inserting element at specific position like

  

fruits = ["Apple", "Mango", "Banana"]
fruits.insert(1, "Orange")
print(fruits)

Output:    
[‘Apple’,’Orange’,’Mango’,’Banana’]

2.5.7 Remove Element:

There are several methods to remove items from a list like remove(),pop(),del,clear().

Using Remove() Method:

The remove() method removes the specified item:

fruits = ["Apple", "Mango", "Banana"]
fruits.remove("Banana")
print(fruits)

Output:        
    [‘Apple’,’Mango’]

2.5.8 Using pop() Method:

The pop() method removes the specified index, (or the last item if index is not specified):

fruits = ["Apple", "Mango", "Banana"]
fruits.pop()
print(fruits)

Output:
    [‘Apple’,’Mango’]

2.5.9 Using del Keyword:

The del keyword removes the specified index:

  

fruits = ["Apple", "Mango", "Banana"]
del fruits[0]
print(fruits)

Output:    
    [’Mango’,’Banana’]

2.9.10 The clear() method empties the list:

fruits = ["Apple", "Mango", "Banana"]
fruits.clear()
print(fruits)