Python Tutorial Python Advanced Python References Python Libraries

Python - Lists



The List is a type of data container in Python which is used to store multiple data in one variable. It can contain elements of different data types. Elements in a list are ordered which can be accessed using index number.

Create List

List can be created by separating it's elements using comma , and enclosing them with square bracket [ ]. Additionally, it can also be created using list() function and list comprehension.

#List with multiple datatypes
Info = ['John', 25, 'London']  
print(Info)

#Creating list using list function
colors = list(('Red', 'Blue', 'Green')) 
print(colors)

#Creating list using list comprehension
x = [1, 2, 3, 4, 5]
y = [i*i for i in x]    
print(y)

The output of the above code will be:

['John', 25, 'London']
['Red', 'Blue', 'Green']
[1, 4, 9, 16, 25]

Access element of a List

An element of a list can be accessed with it's index number. In Python, index number starts with 0 in forward direction and -1 in backward direction. The figure below describes the indexing concept of a list.

List Indexing:

Python Lists Indexing

The example below describes how to access elements of a list using its index number.

weekday = ['MON', 'TUE', 'WED', 'THU', 'FRI']

#forward indexing
print(weekday[1]) 

#backward indexing 
print(weekday[-1])  

The output of the above code will be:

TUE 
FRI   

Access range of elements of a List

Range of elements of a list can be selected using statement like [startIndex : endIndex] where end_index is excluded. If start_index and end_index are not mentioned then it takes first and last index numbers of the list respectively.

weekday = ['MON', 'TUE', 'WED', 'THU', 'FRI']
print(weekday[1:3])
print(weekday[-5:-1],"\n")

print(weekday[1:])
print(weekday[:-3],"\n")

print(weekday[:])

The output of the above code will be:

['TUE', 'WED']                         
['MON', 'TUE', 'WED', 'THU']            

['TUE', 'WED', 'THU', 'FRI']            
['MON', 'TUE']                          

['MON', 'TUE', 'WED', 'THU', 'FRI']     

Modify value of an Element

To change element's value, assign new value using it's index.

Info = ['John', 25, 'London'] 
#value at index=0 changed to 'Marry'
Info[0] = 'Marry'  
print(Info)

The above code will give the following output:

['Marry', 25, 'London']

Add elements in a List

Below mentioned methods are used to add elements in a list:

  • append() - add an element to the end of a list.
  • insert() - insert an element at specified index of the list.
days = ['MON', 'TUE', 'WED', 'THU', 'FRI', 'SAT']
# add this element in last of the list
days.append('SUN')   
print(days)

month = ['JAN', 'FEB', 'MAR', 'MAY']
# add 'APR' at index=3 of the list
month.insert(3,'APR') 
print(month)

The output of the above code will be:

['MON', 'TUE', 'WED', 'THU', 'FRI', 'SAT', SUN']
['JAN', 'FEB', 'MAR', 'APR', 'MAY']

Delete elements of a List

Below mentioned methods/keywords is used to delete elements from a list:

  • remove() - deletes first occurrence of a specified element from the list.
  • pop() - deletes element at specified index or last element if index is not specified.
  • clear() - deletes all elements of a list.
  • del - deletes a element or range of elements or list itself.
number = [10, 50, 50, 100, 1000]
#delete first occurrence of 50.
number.remove(50)    
print(number)

number = [10, 50, 50, 100, 1000]
#delete element at index=3.
number.pop(3)        
print(number)

number = [10, 50, 50, 100, 1000]
#delete last element from the list.
number.pop()        
print(number)

number = [10, 50, 50, 100, 1000]
#delete all elements from the list.
number.clear()     
print(number)

The above code will give the following output:

[10, 50, 100, 1000]
[10, 50, 50, 1000]
[10, 50, 50, 100]
[]

The del keyword is used to delete an element or range of elements or list itself.

number = [10, 50, 50, 100, 1000]
#delete element at index=3.
del number[3]       
print(number)

number = [10, 50, 50, 100, 1000]
#delete element at index=1,2 and 3.
del number[1:4]     
print(number)

number = [10, 50, 50, 100, 1000]
#delete list 'number'.
del number          
print(number)

The above code will give the following output:

[10, 50, 50, 1000]
[10, 1000]

Traceback (most recent call last):
  File "Main.py", line 14, in <module>
    print(number)
NameError: name 'number' is not defined

List Length

The len() function can be used to find out total number of elements in a list, tuple, set or dictionary.

number = [10, 50, 50, 100, 1000, 1000]
print(len(number))

The output of the above code will be:

6

Loop over List

For loop over List:

for loop can be used to access each element of a list.

colors = ['Red', 'Blue', 'Green']
for x in colors:
    print(x)

The output of the above code will be:

Red
Blue
Green

While loop over List

By using while loop and len() function, each element of a list can be accessed.

colors = ['Red', 'Blue', 'Green']
i = 0
while i < len(colors):
    print(colors[i])
    i = i + 1

The above code will give the following output:

Red
Blue
Green

Check an element in the List

If control statement is used to check whether the list contains specified element or not.

colors = ['Red', 'Blue', 'Green']
if 'white' in colors:
  print('Yes, white is an element of colors.')
else:
  print('No, white is not an element of colors.')

The above code will give the following output:

No, white is not an element of colors.

Copy List

There are several ways to create a copy of the list.

  • = operator: Creates a reference of the list. Any change in old list modifies new list also.
  • copy(): Creates an independent copy of a list.
  • list(): Creates an independent copy of a list.
colors = ['Red', 'Blue', 'Green']
mycolor = colors
yourcolor = colors.copy()
hiscolor = list(colors)

print(mycolor)     
print(yourcolor)   
print(hiscolor, "\n")    

#delete last element in 'colors'
colors.pop()       

print(mycolor)     
print(yourcolor)   
print(hiscolor)    

The output of the above code will be:

['Red', 'Blue', 'Green']      
['Red', 'Blue', 'Green']      
['Red', 'Blue', 'Green']      

['Red', 'Blue']               
['Red', 'Blue', 'Green']      
['Red', 'Blue', 'Green']      

Join Lists

There are several ways to join lists.

  • + operator: Used to join two lists into a new list.
  • append(): Appends all elements of one list into another.
  • extend(): Adds all elements of one list into another.
colors = ['Red', 'Blue', 'Green']
numbers = [10, 20]
mylist1 = colors + numbers
print(mylist1)

colors = ['Red', 'Blue', 'Green']
numbers = [10, 20]
for i in numbers:
  colors.append(i)
print(colors)

colors = ['Red', 'Blue', 'Green']
numbers = [10, 20]
colors.extend(numbers)
print(colors)

The output of the above code will be:

['Red', 'Blue', 'Green', 10, 20]  
['Red', 'Blue', 'Green', 10, 20]  
['Red', 'Blue', 'Green', 10, 20]  




5