Instagram
youtube
Facebook
Twitter

Python List

  • List in python is a sequential datatype.
  • It is used to store n number of data items in sequential form.
  • Each data item in the list has an index value.
  • List works in the same way how array used to work in c++ or java. 
  • List is defined using square brackets [].
#Defining List in Python

a = [14, 22, 34, 49, "Codersdaily"]
print(a)

 

Properties of List:

  • A list is a sequential data type which means each data item inside the list has a defined position or index value.
  • The list is an ordered datatype.
  • The list is mutable. You can update, insert, delete items inside a list.
  • Each data item in the list holds two memory locations. Which makes the list slower than tuple and other data types.
  • A list allows repetitions.

 

Methods in list

List in python has a lot of methods which include methods to append values, sort lists, insert data items. Which makes the list an easy-to-use datatype. Here are some of the popular methods which are extensively used in the list.

 
Method Definition Code
append() Append is used to add an element to the last index of the list
a =[1,2,3,4,5]
a.append(6)
print(a)


#Output - [1,2,3,4,5,6]

 

clear() Removes all the elements from the list
a =[1,2,3,4,5,6]
a.clear()
print(a)

 

copy() Creates a copy of the list
a =[1,2,3,4,5,6,7]
x = a.copy()
print(x)

 

count() Returns the number of elements with a specified value.
a =[1,2,3,4,5,6]
x = a.count(2)
print(x)

 

index() Returns the index value of a particular element.
a =[1,2,3,4,5,6]
x = a.index(1)
print(X)

 

insert() It is used to insert a value at a defined index inside the list.
list1 =[1,2,3,4,5,,6,7]
list1.insert(2,33) #Here 2 is the index and 33 is the data item inserted
print(list1)

 

pop() It is used to remove the last data item from the list.
a =[1,2,3,4,5,6,7]
a.pop()
print(a)

 

remove()  It is used to remove a particular item from a list.
a =[1,2,3,4,5,6,7]
a.remove(2)
print(a)

 

reverse() It is used to reverse a list.
a =[1,2,3,4,5,6,7]
a.reverse()
print(a)

 

sort() It is used to sort a particular list.
a =[122,4,,5,6,77,888,9,0]
a.sort()
print(a)