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]:8list characters :list_chars[0]:a list_chars[1]:b list_chars[2]:c list_chars[3]:dlist strings :list_str[0]:foodlist_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
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
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
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']
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 (=).
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.
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.
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()