AlphaCodingSkills

Python - Lists


Advertisements

Previous Page Next Page

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)

Output

['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 below figure and example describe the indexing concept of a list.

List Indexing:

Python Lists Indexing

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

#forward indexing
print(weekday[1]) 

#backward indexing 
print(weekday[-1])  

Output

TUE 
 
FRI   

Access range of elements of a List

Range of elements of a list can be selected using statement like [start_index : end_index] 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])

print(weekday[1:])
print(weekday[:-3])

print(weekday[:])

Output

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

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

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

Modify element's value

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)

Output

['Marry', 25, 'London']

Add elements in a List

Below mentioned methods is 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)

Output

['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)

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)

Output

[10, 50, 50, 1000, 1000]

[10, 1000, 1000]

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))

Output

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)

Output

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

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.')

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)    

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

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

Output

['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)

Output

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

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

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





List Methods & Functions
MethodsDescription
append() Adds a specified element to the end of the list
clear() Deletes all elements from the list
copy() Creates a copy of the list into a new list
count() Returns the number of occurrence of a specified element in the list
extend() Adds an element or iterable at the end of the list
index() Returns the index of first occurrence of a specified element in the list
insert() Adds a specified element at specified index in the list
pop() Deletes an element at specified index or last element of the list
remove() Deletes first occurrence of a specified element in the list
reverse() Reverses order of all elements in the list
sort() Sorts elements of the list in ascending or descending order with specified sorting criteria
FunctionsDescription
len() Returns total number of elements in the list
list() List function/constructor is used to create list from iterable like list, tuple, set, string and dictionary, etc.

Previous Page Next Page