You are currently viewing Python lists | Python List For Loop | Python 3.8
python lists

Python lists | Python List For Loop | Python 3.8

In Python lists are the container of data which contain different type of data . In lists the data my be number, string , date and Boolean. Python has many built in sequence but the most common use is tuples. 

So in this tutorial you will learn everything about list , how they are created, how to add element in list or removing a specific element in list, read the index of lists. In lit each element have a unique index .

The python lists are created in simple Python 3.8 IDLE click here to download it.

Example :

list1 = [1,3,5,7]

The above list contain a 4 number the 1 is index 0, 3 is index 1, 5 is index 2 and 7 is 4 and so on.

Learn python Object Oriented Programming.

How To Create  Python Lists:

The python lists is created with square bracket [] and all the item (elements) are written in the bracket.  So in this article you will learn all types of list which contain different types of data.

#Empty List
a = []
#integer list
list_a = [1,2,3,4,5,6]
#mixed data type list
list_b =[2,5,7,10.4,"hello","25-04-2021"]
print ("Mixed Data Type List :",list_b)
The output is :
Mixed Data Type List : [2, 5, 7, 10.4, 'hello', '25-04-2021']

Get all Python List Items:

To get all the item in the single  array we use the python built in function print.

Example :

# student list
student =["sadaqat","basharat","salman","narjis"]
The Output is:
Roll No : [1, 2, 3, 4]

Nested List:

In python nested list is that list which contain multiple list data or another list data. The following example is nested list.

#nested list:
my_list =["math","english",[1,2,3,4],10.7]
print(my_list)

The output is :
['math', 'english', [1, 2, 3, 4], 10.7]

The Access Of Item From The List:

In python lists there are many method to get the required items from the list. In python lists each item have a unique index for example a list have 5 elements its index 0 to 4.

We can get the specific item from the list we the the index operator[] with python built in function print(). When you call the item from the list if you index is correct then python will show accurate output other it will show the error.

So in this situation there are  two types of error my how the 1st is IndexError and 2nd is TypeError.

The IndexError is appear when trying a index number which is not contain in the list. Then it will appear.

The TypeError is appear when you trying to get the index with alphabetic character. So in this situation it will show error “the index must be the integer”.

Examples:

We have a list of subject which contain four student or in other word in have four item. So I want to get first student. I will rite the follow function.

subject = ["math","englih","chemistry","islamic study"] 
print ("subject list:",student[0])

The output is:
subject list: math

Get the 2nd item from the subject list:
print ("subject list:",subject[2])
output is:
subject list: chemistry

subject = ["math","englih","chemistry","islamic study"] 

print ("subject list:",subject[4])
the output is :

Traceback (most recent call last):
File "G:/Project/sharafat/oops/lists.py", line 16, in <module>
print ("subject list:",subject[4])
IndexError: list index out of range

In the above example the student list have four item with index 0 to 3 and have enter index[4] which not exist in the list. So IndexError apprear.

subject = ["math","englih","chemistry","islamic study"] 
print ("subject list:",subject[a])

Output Is :
Traceback (most recent call last):
File "G:/Project/sharafat/oops/lists.py", line 16, in <module>
print ("subject list:",subject[a])
TypeError: list indices must be integers or slices, not list

The above error is TypeError because I write the wrong index [a] then it will show me list indices must be integers or slices. It called the TypeError.

Negative Indexing In python :

Python will allow you to call the index with negative values for example.

subject = ["math","englih","chemistry","islamic study"]

print ("subject list:",subject[-1])
Output is:
subject list: islamic study

In the aboe list the islamic study is the last item and it have index[3] and when you call it negative index value you should try index[-1].

# subject list
subject = ["math","englih","chemistry","islamic study"]
#print function
print ("subject list:",subject[-3])
Output is :
subject list: englih

Know the Length Of List In Python:

Here we write the small built in function len(name of list) to know the length of any list in python.

# subject list
subject = ["math","englih","chemistry","islamic study"]
#print function
print ("The length of subject list is:",len(subject))
Output is :
The length of subject list is: 4

Adding Item In Python lists

To add in the item in previous python list we use the append() function . I want to add one more subject in subject list. 

Example:

# subject list
subject = ["math","englih","chemistry","islamic study"]
#print function
subject.append("bio")
print ("subject list:",subject)
OutPut Is :
subject list: ['math', 'englih', 'chemistry', 'islamic study', 'bio']

Insert The Item In Specific Index:

To insert the item in the python lists we use the insert method () in specific index ().

Example :

I want to insert one more subject in subject list at index(1). We write the following command.

# subject list
subject = ["math","englih","chemistry","islamic study"]
#print function
subject.insert(1,"economics")
print ("subject list:",subject)
OutPut is:
subject list: ['math', 'economics', 'englih', 'chemistry', 'islamic study']

Extend List:

Extend list mean if you want to transfer a list item to another list then extend method is used.

Example :

list_a=[1,2,3,4]
list_b=[2,4,6,8]
list_b .extend(list_a )
print(list_b )
OutPut is:
[2, 4, 6, 8, 1, 2, 3, 4]

Change The List Item:

To change  or replacing the item from the list we mention the index[] number and  then writhe the new item in double quote “”.

Example :

In our subject list I want to change the index[1] which is Eng and replace with economic.

# subject list
subject = ["math","englih","chemistry","islamic study"]
#print function
subject[1]="economics"
Output Is:
subject list: ['math', 'economics', 'chemistry', 'islamic study']

Removing the Item From Python Lists:

To removing the specific  item from the list we use the remove () method, and write the item from the list with double quote “”. If the item which you write is not appear in the list it will show  the error.

Example :

# subject list
subject = ["math","englih","chemistry","islamic study"]
#print function
subject.remove("chemistry")
print ("subject list:",subject)
outPut Is:
subject list: ['math', 'englih', 'islamic study']

If you enter the misspelling or wrong item in the remove method then it will show you the ValueError like below.

Traceback (most recent call last):
File “G:/Project/sharafat/oops/lists.py”, line 17, in <module>
subject.remove(“chemistr”)
ValueError: list.remove(x): x not in list

Sort Python lists:

Sorting a record in any program is very important , there are two types of sorting record or list 1st is Ascending and 2nd Descending. In python we use the pop method to ascending the list and reverse method is use for descending the list.

Example:

# subject list
subject = ["math","englih","chemistry","islamic study"]
#sorting list
subject.pop()
print("Ascening List :",subject)
Output is:
Ascening List : ['math', 'englih', 'chemistry']

Example 2 : Reverse Method

# subject list
subject = ["math","englih","chemistry","islamic study"]
#sorting list
subject.reverse()
print("Ascening List :",subject)
Output is:
Reverse order : ['islamic study', 'chemistry', 'englih', 'math']

Use If Else Statement In Python Lists

In python list now we apply the conditions in lists, these conditions my be the single or multiple. We try to access the required index in condition with user input method.

Example :

# subject list
subject = ["math","englih","chemistry","islamic study"]

#user input
sub= input("Enter Subject Name :")

#single condion
if sub == subject[0]:
print("This Subject available :",sub)
else:
print("This Subject is not available :", sub)
user input:
Enter subject name : math
Output is :
This Subject available : math

In other case else statement if user input a subject which is not in subject list at index[0]. then following statement read.

user input:
Enter subject name : bio
Output is :
This Subject is not available : bio

Read The Multiple Index In Python Lists:

Example :

# subject list
subject = ["math","englih","chemistry","islamic study"]

#user input
sub= input("Enter Subject Name :")

#access multiple index
if sub == subject[0] or [1] or [2] or [3]:
print("This Subject available :",sub)
else:
print("This Subject is not available :", sub)
User input:
Enter Subject Name :chemistry
output is:
This Subject available : chemistry

Python Lists For Loop

In object oriented programming a for loop is use to iterating over a sequence (a block of code list, set, tuple or dictionary).

Example: 

# subject list
subject = ["math","englih","chemistry","islamic study"]
#use for loopfor x in student:
print(x)
The output is:
math
englih
chemistry
islamic study

This Post Has One Comment

Comments are closed.