Special Offer - Enroll Now and Get 2 Course at ₹25000/- Only Explore Now!

All Courses
Python List

Python List

May 20th, 2019

Concepts for Python List

Python contains six (6) built-in sequences types, where List are said to be the common one. Python Lists are similar to arrays that are stated in various other languages. It is always not necessary to have standardized lists and this stands out to be an utmost influential tool available in Python. A Python list may contain different Datatypes such as strings, objects, and integers. Python Lists are helpful to implement queues and stacks. Once the Python lists are created, they can be altered as the lists are mutable.

  • Python List is one kind of container in Data Structures and these lists are utilized to stock up numerous data.
  • Python Lists are written as a list of value using comma-separated between square brackets.
  • Python Lists are always ordered and have a certain count. The list elements are indexed as per a certain classification and the list indexing is started with ‘0’.
  • Python permits to have negative indexing as well for its sequences. Index -1 indicates the last item, -2 indicates the second last item and it continues.
  • Each element of the Python List has a fixed place in the existing list and has its own discrete place and reliability.
  • Python List is a super helpful tool for protecting a data sequence and moreover iterating over the same.
  • Python list is similar to the arrays C & C++ Programming language
  • The Python list is a data structure it’s a combination of homogeneous or heterogeneous data types.
  •  Python list Data element stored the sequence manner.

Python Lists | Python Tutorial For Beginners

Python List Creation

List creation in Python is done by placing all the elements separated by commas, within a square bracket [ ]. As already mentioned above, a list can contain any number of items which can be of dissimilar types such as float, integer, string and so on. Below is an example for Python list creation:
# list of integers
my_list = [1, 2, 3] Python List that has another list within the same syntax as an item is called nested list. For example,
# nested listmy_list = [“mouse pad”, [8, 2, 6], [‘a’]]

Access elements from a Python List

  • Make use of index operator [] to access an item from a Python List. Index starts from ‘0’ and hence the first element is stored at 0th index in the list, second element at 1st index and it continues.
  • If you try to access the elements by any other method, IndexError will be raised. Note that all the index must be an integer.
  • In Python List, if you are using float or any other string types, the result would be
  • In Python List, you can use the Nested index to access the Nested list.
  • In Python List, you can use Slicing operator (colon) to access a variety of items.

How to access the python List Elements:

Two type of indexing python-list access

  • Forward Indexing
  • Backward indexing

Forward indexing

The forward indexing starting element ‘mostly ‘0’ value is positive and an index value of (n-1)

Example Code :
list_nums = [30,40,50,60]

list_flt_nums=[2.5,3.6,4.8,8.5]
 
list_chars =['a','b','c','d']

list_str=["food","egg","cricket","water"]
 
list_all=[20,25.5,"fruits",'x']

print "list numbers"

for i in range(len(list_nums)):

print "list_num[%d]:%d"%(i,list_nums[i])
 
print "list float numbers"

for i in range(len(list_flt_nums)):

print "list_flt_nums[%d]:%d"%(i,list_flt_nums[i])
 
print "list characters"

for i in range(len(list_chars)):
 
print "list_chars[%d]:%s"%(i,list_chars[i])

print "list strings"

for i in range(len(list_str)):
 
print "list_str[%d]:%s"%(i,list_str[i])

print "list all"

for i in range(len(list_all)):

print "list_all[",i,"]:",list_all[i]
OutPut:
list numbers :
list_num[0]:30 
list_num[1]:40 
list_num[2]:50 
list_num[3]:60 
list float numbers :
list_flt_nums[0]:2 
list_flt_nums[1]:3 
list_flt_nums[2]:4 
list_flt_nums[3]:8
list characters :
list_chars[0]:a 
list_chars[1]:b 
list_chars[2]:c 
list_chars[3]:d
list strings :
list_str[0]:food
list_str[1]:egg 
list_str[2]:cricket 
list_str[3]:water 
list all :
list_all[ 0 ]: 20 
list_all[ 1 ]: 25.5 
list_all[ 2 ]: food 
list_all[ 3 ]: x 

Backward Indexing

 The Backward indexing starting element ‘mostly ‘n-1’ value is positive and an index value of (-n+(n-1))=-1

Example code :
list_nums = [20,30,40,50]
list_flt_nums=[2.5,3.6,4.8,8.5] 
list_chars =['a','b','c','d'] 
list_str=["food","egg","cricket","water"] 
list_all=[20,25.5,"apple",'x'] 
print "list numbers" 
n=len(list_nums) 
for i in range(n): 
print "list_num[%d]:%d"%(i-n,list_nums[i]) 
n=len(list_flt_nums) 
print "list float numbers" 
for i in range(n): 
print "list_flt_nums[%d]:%d"%(i-n,list_flt_nums[i]) 
n=len(list_chars) 
print "list characters" 
for i in range(n): 
print "list_chars[%d]:%s"%(i-n,list_chars[i]) 
n=len(list_str) 
print "list strings" 
for i in range(n): 
print "list_str[%d]:%s"%(i-n,list_str[i]) 
n=len(list_all) 
print "list all" 
for i in range(n): 
print "list_all[",i-n,"]:",list_all[i] 

Output:

list numbers

list_num[-4]:20
list_num[-3]:30 
list_num[-2]:40 
list_num[-1]:50 
list float numbers 
list_flt_nums[-4]:2 
list_flt_nums[-3]:3 
list_flt_nums[-2]:4 
list_flt_nums[-1]:8 
list characters :
list_chars[-4]:a 
list_chars[-3]:b 
list_chars[-2]:c 
list_chars[-1]:d 
list strings :
list_str[-4]:food 
list_str[-3]:egg 
list_str[-2]:cricket 
list_str[-1]:water 
list all :
list_all[ -4 ]: 2 
list_all[ -3 ]: 25.5 
list_all[ -2 ]: apple 
list_all[ -1 ]: x

How to Create multiple elements in Python-List

Example Code :
We have to change the data. 
list_nums=[2,3,4,5,6] 
print "list_nums is" 
print the list_nums # Print the without changing the value of the element 
list_nums[3]=15 
print "list_nums after 1st iteration change" 
print list_nums #list is printing with changing the elements at index 3 
list_nums[0]=8 
list_nums[1]=4 
print "list_nums after 2nd iteration change" 
print list_nums #list is printing with changing the elements at index 0,1 
Output :
[2, 3, 4, 5, 6] list_nums after 1st iteration change 
[1, 2, 3, 15, 5] 
list_nums after 2nd iteration change 
[8, 4, 3, 15, 5]

How to Replacing value with Python-List

A Replacing python-list element value means sample list value for multiple time with all element python-list

Example code:
list =[2,3,4] 
print list*1 #No value replication 
print list*2 #one time value replication 
print list*3 #two time value replication 
print list*4 #three time value replication 
Output :
[2, 3, 4] [2, 3, 4, 2, 3, 4] 
[2, 3, 4, 2, 3, 4, 2, 3, 4] 
[2, 3, 4, 2, 3, 4, 2, 3, 4, 2, 3, 4] 

How to create Add element, Extended the list, Delete value for the python-List?

Example Code :
list1=[2,3,4] 
list2=[5,6,7] 
list=list1+list2 
print list 
Output :
[2, 3, 4, 5, 6, 7] 

Python-List to Delete the Value using Two Method

We delete the value of complete python-list, bulk data element value, and the single element value in python

  •  del method
  •  clear method
Example Code:
or_list1 =[2,3,4,5] 
or_list2 =[2.2,3.5,4.6,5.3] 
print or_list1 
print or_list2 
del or_list1[0] #delete first element 
print or_list1 
del or_list1[:] #delete complete list 
print or_list1 
del or_list2[0:2] #delete element between 0,2 
print or_list2 
del or_list2[0:len(or_list2)] #delete complete list 
print or_list2 
Output :
[2, 3, 4, 5] [2.2,3.5,4.6,5.3] [3, 4, 5] [] [4.6,5.3] [] 

Clear method:

In this clear method is used clear the data value complete list.
list_name.clear()

Example :
or_list =[2,3,4,5] 
print (or_list) 
or_list.clear() 
print (or_list) 
Output :
[2, 3, 4, 5] 

Functions on Python Lists

  • Use ‘len’ function to retrieve the length of the Python list.
  • Use ‘enumerate’ function to retrieve index and the value of the element from the list.
  • If there are two Python lists, use ‘cmp’ to compare elements available in both the lists.
  • Use ‘max’ to retrieve the item that has the maximum value from the list.
  • Use ‘min’ to retrieve the item that has the minimum value from the list.

So, now it’s time to start your coding with Python Programming Language using all the above mentions methods, functions, and syntax.

MAX METHOD:

It is used to find out the biggest element in the python list

MIN METHOD:

It is used to find out the smallest element in the python list

COUNT METHOD:

Count Method is used to count the occurrence of a specific element in the list.

LEN METHOD:

In this Method used to count the value of the total element in the list.

SUM METHOD:

In this Method is used to find out the sum of the elements in the list.

Example Code :
list=[356,115,46,350,2500,31] 
print "Biggest value of element in list:",max(list) 
print "Smallest value of element in list:",min(list) 
print "sum of value elements in list:",sum(list) 
print "count the number value of elements in list:",len(list) 
print "count the element occurrence value no.of times:",list.count(350) 
Output :
The biggest element in the list: 2500 
The smallest element in the list: 31 
the sum of elements in the list: 3398 
count the number of elements in the list: 6 
count the element occurrence no.of times: 2 
Lists can be thought of the most general version of a sequence in Python. Unlike strings, they are mutable, meaning the elements inside a list can be changed! Lists are constructed with brackets [] and commas separating every element in the list.
In this section we will learn about:

  • Creating lists
  • Indexing and Slicing Lists
  • Basic List Methods
  • Nesting Lists
  • Introduction to List Comprehensions

Creating lists

Assign a list to an variable named my_list list1 = []
list2 = list()
my_list = [1,2,3]
print(type(list1))
print(type(list2))
print(type(my_list))
<class 'list'="">
<class 'list'="">
<class 'list'="">
my_list1 = [4.0,5.0,6]
my_list2 = [4,5.0+3j,"abc"
print(my_list1)
print(my_list2)
[4.0, 5.0, 6]
[4, (5+3j), 'abc']

Combining lists

list_combined =my_list1+my_list2 + [7.0,8.0,9+2j]
print(list_combined)
[4.0, 5.0, 6, 4, (5+3j), 'abc', 7.0, 8.0, (9+2j)]

Indexing and Slicing

Indexing and slicing work just like in strings. Let’s make a new list to remind
ourselves of how this works:

just take the 1st element at the list
Input:
list_combined[0]
Output
4.0
retrieve the 1st element until third
Input:
list_combined[0:3]
Output
[4.0, 5.0, 6]
retrieve the 2nd element until the end of the list
Input:
list_combined[2:]
Output
[6, 4, (5+3j), 'abc', 7.0, 8.0, (9+2j)]

We can also use + to concatenate lists, just like we did for strings.

add_tolist = list_combined + ["def","ghi"]
list_direct = [4.0, 5.0, 6, 4, (5+3j), 'abc'] + ['def', 'ghi']
print(add_tolist,list_direct)
[4.0, 5.0, 6, 4, (5+3j), 'abc', 7.0, 8.0, (9+2j), 'def', 'ghi'] [4.0, 5.0,
6, 4, (5+3j), 'abc', 'def', 'ghi']

Duplicating list

Example:
duplicated_list = add_tolist * 3
print(duplicated_list)
[4.0, 5.0, 6, 4, (5+3j), 'abc', 7.0, 8.0, (9+2j), 'def', 'ghi', 4.0, 5.0,
6, 4, (5+3j), 'abc', 7.0, 8.0, (9+2j), 'def', 'ghi', 4.0, 5.0, 6, 4,
(5+3j), 'abc', 7.0, 8.0, (9+2j), 'def', 'ghi']

Methods of Python List

  • insert()
  • clear()
  • sort()
  • copy()
  • reverse()
  • index()
  • append()
  • extend()
  • remove()
  • pop()
  • count()

Now, let us have a short discussion on each Python List methods with examples so that you can have a hands-on experience.

Add or change elements to a Python List

Unlike string or tuple, list elements can be changed as lists are mutable.
To change a range of items or an item, you can use the assignment operator (=).

Example:
# mistake valuesodd = [2, 4, 6, 8] # change the 1st item    odd[0] = 9#
Output:
[9, 4, 6, 8] print(odd)

append()

You can use append()to add one item to a list as shown in the below example.

Example:
odd = [1, 3, 5, 7] odd.append(9)
[/su_table]
Output:
[1, 3, 5, 7, 9] print(odd)
Cities =["Chennai","Bangalore", "Delhi","Kolkatta"]
#Append
print("Cities - {} ".format(Cities))
#add a new item to the list
Cities.append("Hyderabad")
print("Cities - {} ".format(Cities))
#Cities.append(["Mumbai","Pune"])
#print("Cities - {} ".format(Cities))
Cities - ['Chennai', 'Bangalore', 'Delhi', 'Kolkatta']
Cities - ['Chennai', 'Bangalore', 'Delhi', 'Kolkatta', 'Hyderabad']

extend()

Use extend() to add numerous items to the Python List as shown in the below example.

Example:
odd.extend([9, 11, 13, 15, 17, 19, 21])
Output:

[1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21]

print(odd)

To extend the items of a list with another list of items, lets add another city list to existing one
Cities =["Chennai","Bangalore", "Delhi","Kolkatta","Hyderabad"]
NewCities = ["Mumbai","Pune","Agra","Kanpur","Noida","Visakhapatnam"]
print("Cities - {}".format(Cities))
print("New Cities - {}".format( NewCities))
resultCities=Cities.extend(NewCities)
print(resultCities)
print("Cities after Extend {}".format(Cities))
Cities - ['Chennai', 'Bangalore', 'Delhi', 'Kolkatta', 'Hyderabad']
New Cities - ['Mumbai', 'Pune', 'Agra', 'Kanpur', 'Noida', 'Visakhapatnam']
None
Cities after Extend ['Chennai', 'Bangalore', 'Delhi', 'Kolkatta',
'Hyderabad', 'Mumbai', 'Pune', 'Agra', 'Kanpur', 'Noida', 'Visakhapatnam']

insert()

Use the method insert() to insert one item at an anticipated location or you can also insert multiple items. Look into the below examples for more clarification.

Example:

odd = [1, 9]

odd.insert(1,5)

Output:
[1, 5, 9] print(odd)
Example for inserting one item:
odd[2:2] = [3, 5]
Output:
[1, 3, 5, 7, 9] print(odd)
Add an item to a particular postion/index
Cities =["Chennai","Bangalore", "Delhi","Kolkatta","Hyderabad"]
Cities.insert(10,"Mumbai")
print("Cities - {}".format(Cities))
#Cities.insert("Pune")
#print("Cities - {}".format(Cities))
Cities - ['Chennai', 'Bangalore', 'Delhi', 'Kolkatta', 'Hyderabad',
'Mumbai']

operator ‘+’

Use the operator ‘+’ to combine two (2) lists and this type of process is called concatenation.

odd = [1, 3, 5, 9]

Output: [1, 3, 5, 9, 7, 5, 9]

print(odd + [7, 5, 9])

operator ‘*’

The operator ‘*’ is used to repeat a list for the provided count. Refer the below example:

Output: ["re", "re", "re", “re”]
print(["re"] * 4)

clear()

#Clear
#Removes all the items from the list
Cities.clear()
print(Cities)

index()

index
GetIndex = Cities.index("Chennai")
print(GetIndex)
GetIndex = Cities.index("Noida")
print(GetIndex)
9

Remove or Delete Elements from a List

In Python List, to delete one or more items, use the keyword del. You can use the same keyword to delete the entire list.

Example:
my_list = [‘r’,’e’,’s’,’u’,’l’,’t’] delete one itemdel my_list[3]
Output:
[‘r’, ‘e’, ‘s’, ‘l’, ‘t’] print(my_list)

remove()

Use the method remove() to eliminate the specified item from the list.

my_list = [‘f’,’a’,’i’,’l’,’u’,’r’,’e’]

my_list.remove(‘i’)

Output:
'f','a','l','u','r','e']
print(my_list)
Cities =["Chennai","Bangalore", "Delhi","Kolkatta","Hyderabad", "Kolkatta"]
print("Cities - {}".format(Cities)) Cities.remove("Kolkatta")
print("Cities - {}".format(Cities))
#Cities.remove("Kolkatta") #print("Cities - {}".format(Cities))
#Cities.remove("Kolkatta") #print("Cities - {}".format(Cities)) print("After remove Operation , Cities - {}".format(Cities))
Cities.pop(Cities.index("Kolkatta"))
print("Cities - {}".format(Cities))
Cities - ['Chennai', 'Bangalore', 'Delhi', 'Kolkatta', 'Hyderabad', 'Kolkatta'] Cities - ['Chennai', 'Bangalore', 'Delhi', 'Hyderabad', 'Kolkatta']
Cities - ['Chennai', 'Bangalore', 'Delhi', 'Hyderabad'] After remove Operation , Cities - ['Chennai', 'Bangalore', 'Delhi', 'Hyderabad']
ValueError
Traceback (most recent call last) in ()
#print("Cities - {}".format(Cities))
print("After remove Operation , Cities - {}".format(Cities)) --->
Cities.pop(Cities.index("Kolkatta"))
print("Cities - {}".format(Cities))
ValueError: 'Kolkatta' is not in list

pop()

Use the method pop()to eliminate an item at the specified index. If an index is not given, pop() method is used to remove and return the last item and this method is helpful in implementing lists as stacks, i.e. first in, last out data structure.

Cities =["Chennai","Bangalore", "Delhi","Kolkatta","Hyderabad"]
print("Cities - {}".format(Cities))
Cities.pop()
print("After Pop Operation , Cities - {}".format(Cities))
Cities - ['Chennai', 'Bangalore', 'Delhi', 'Kolkatta', 'Hyderabad']
After Pop Operation , Cities - ['Chennai', 'Bangalore', 'Delhi',
'Kolkatta']

Left out methods in Python List

count()

Method count()is to count the number of times that an element occurred in a Python List and returns the same. Syntax for count()method is given below:
list.count(element)

Add the Items Back
Cities =["Chennai","Bangalore", "Delhi","Kolkatta","Hyderabad"]
print(Cities)
#Count - Used to find the count of an item
count_givencity = Cities.count("Chennai")
print(count_givencity)
Cities.append("Chennai")
print(Cities)
count_givencity = Cities.
count("Chennai")
print("Count of City after adding again {}".format(count_givencity))
['Chennai', 'Bangalore', 'Delhi', 'Kolkatta', 'Hyderabad']
['Chennai', 'Bangalore', 'Delhi', 'Kolkatta', 'Hyderabad', 'Chennai']
Count of City after adding again 2

sort()

In Python List, to sort the elements of a provided list in order, either ascending or descending, use the method sort().
Syntax: list.sort(key=…, reverse=…)
Though the method sort() does not need any additional parameters, this Python List method has two (2) non-compulsory parameters, which are reverse and key.

Example:
Cities =["Chennai","Bangalore",
"Delhi","Kolkatta","Hyderabad","Mumbai","Pune","agra","Kanpur","Noida","Vis
akhapatnam"]#
#Cities.sort(False, key = None)
print("Cities - {}".format(Cities))
def overlength(e):
return len(e)
def overacharcount(e):
return e.count("a")
Cities.sort()
print(Cities)
print("###########################")
Cities.sort(reverse = True)
print(Cities)
print("###########################")
Cities.sort(reverse = True, key = overlength)
print("Cities - In desc order of Length - {}".format(Cities))
print("###########################")
Cities.sort(reverse = False, key = overlength)
print("Cities - In asc order of Length - {}".format(Cities))
print("###########################")
Cities.sort(reverse = True, key = overacharcount)
print("Cities - In desc order of character 'a' count - {}".format(Cities))
print("###########################")
Cities.sort(reverse = False, key = overacharcount)
print("Cities - In asc order of character 'a' count - {}".format(Cities))
print("###########################")
Cities - ['Chennai', 'Bangalore', 'Delhi', 'Kolkatta', 'Hyderabad',
'Mumbai', 'Pune', 'agra', 'Kanpur', 'Noida', 'Visakhapatnam']
['Bangalore', 'Chennai', 'Delhi', 'Hyderabad', 'Kanpur', 'Kolkatta',
'Mumbai', 'Noida', 'Pune', 'Visakhapatnam', 'agra']
Output:
###########################
['agra', 'Visakhapatnam', 'Pune', 'Noida', 'Mumbai', 'Kolkatta', 'Kanpur', 'Hyderabad', 'Delhi', 'Chennai', 'Bangalore']
###########################
Cities - In desc order of Length - ['Visakhapatnam', 'Hyderabad', 'Bangalore', 'Kolkatta', 'Chennai', 'Mumbai', 'Kanpur', 'Noida', 'Delhi', 'agra', 'Pune'] ###########################
Cities - In asc order of Length - ['agra', 'Pune', 'Noida', 'Delhi', 'Mumbai', 'Kanpur', 'Chennai', 'Kolkatta', 'Hyderabad', 'Bangalore', 'Visakhapatnam'] ###########################
Cities - In desc order of character 'a' count - ['Visakhapatnam', 'agra', 'Kolkatta', 'Hyderabad', 'Bangalore', 'Noida', 'Mumbai', 'Kanpur', 'Chennai', 'Pune', 'Delhi'] ###########################
Cities - In asc order of character 'a' count - ['Pune', 'Delhi', 'Noida', 'Mumbai', 'Kanpur', 'Chennai', 'agra', 'Kolkatta', 'Hyderabad', 'Bangalore', 'Visakhapatnam'] ###########################

copy()

You can copy the list using the operator “=”. But, while modifying the new list, the old list will also get modified. To get the original list unaffected after making the changes to the new list, use the method copy() and this is known as a shallow copy.
Syntax: new_list = list.copy()

reverse()

#Reverses the list
Cities =["Chennai","Bangalore", "Delhi","Kolkatta","Hyderabad"]
Cities.reverse()
#Re Reverse
Cities_1 = Cities[::-1]
print(Cities)
print(Cities_1)
['Chennai', 'Bangalore', 'Delhi', 'Kolkatta', 'Hyderabad']
['Hyderabad', 'Kolkatta', 'Delhi', 'Bangalore', 'Chennai']