Python Tutorial

Introduction Python Features Python Applications System requirements for Python Python Installation Python Basics Python Variables Python Data Types Python IDE Python Keywords Python Operators Python Comments Python Pass Statement

Python Conditional Statements

Python if Statement Python elif Statement Python If-else statement Python Switch Case

Python Loops

Python for loop Python while loop Python Break Statement Python Continue Statement Python Goto Statement

Python Arrays

Python Array Python Matrix

Python Strings

Python Strings Python Regex

Python Built-in Data Structure

Python Lists Python Tuples Python Lists vs Tuples Python Dictionary Python Sets

Python Functions

Python Function Python min() function Python max() function Python User-define Functions Python Built-in Functions Anonymous/Lambda Function in Python

Python File Handling

Python File Handling Python Read CSV Python Write CSV Python Read Excel Python Write Excel Python Read Text File Python Write Text File Read JSON File in Python

Python Exception Handling

Python Exception Handling Python Errors and exceptions Python Assert

Python OOPs Concept

OOPs Concepts in Python Classes & Objects in Python Inheritance in Python Polymorphism in Python Python Encapsulation Python Constructor Static Variables in Python Abstraction in Python

Python Iterators

Iterators in Python Yield Statement In Python

Python Generators

Python Generator

Python Decorators

Python Decorator

Python Functions and Methods

Python Built-in Functions Python String Methods Python List Methods Python Dictionary Methods Python Tuple Methods Python Set Methods

Python Modules

Python Modules Python Datetime Module Python Calendar Module  

Python MySQL

Python MySQL Python MySQL Update Operation Python MySQL Delete Operation

Python MongoDB

Python MongoDB

Python Data Structure Implementation

Python Stack Python Queue Python Hash Table Python Graph

Python Advance Topics

Speech Recognition in Python Face Recognition in Python Python Rest API Python Command Line Arguments Python JSON Python Virtual Environment Type Casting in Python Collections in python Python Enumerate Python Debugger Python DefaultDict

Misc

Python PPTX Python Pickle Python Seaborn Python Coroutine Python EOL Python Infinity Python math.cos and math.acos function Python Project Ideas Based On Django Reverse a String in Python Reverse a Number in Python Python Word Tokenizer Python Trigonometric Functions Python try catch exception GUI Calculator in Python Implementing geometric shapes into the game in python Installing Packages in Python Python Try Except Python Sending Email Socket Programming in Python Python CGI Programming Python Data Structures Python abstract class Python Compiler Python K-Means Clustering List Comprehension in Python3 NSE Tools In Python Operator Module In Python Palindrome In Python Permutations in Python Pillow Python introduction and setup Python Functionalities of Pillow Module Python Argmin Python whois Python JSON Schema Python lock Return Statement In Python Reverse a sentence In Python tell() function in Python Why learn Python? Write Dictionary to CSV in Python Write a String in Python Binary Search Visualization using Pygame in Python Latest Project Ideas using Python 2022 Closest Pair of Points in Python ComboBox in Python Python vs R Python Ternary Operators Self in Python Python vs Java Python Modulo Python Packages Python Syntax Python Uses Python Logical Operators Python Multiprocessing Python History Difference between Input() and raw_input() functions in Python Conditional Statements in python Confusion Matrix Visualization Python Python Algorithms Python Modules List Difference between Python 2 and Python 3 Is Python Case Sensitive Method Overloading in Python Python Arithmetic Operators Design patterns in python Assignment Operators in Python Is Python Object Oriented Programming language Division in Python Python exit commands Continue And Pass Statements In Python Colors In Python Convert String Into Int In Python Convert String To Binary In Python Convert Uppercase To Lowercase In Python Convert XML To JSON In Python Converting Set To List In Python Covariance In Python CSV Module In Python Decision Tree In Python Difference Between Yield And Return In Python Dynamic Typing In Python Abstract design pattern in python Builder design pattern in python Prototype design pattern in Python Creational design patterns in Python

How to

How to convert integer to float in Python How to reverse a string in Python How to take input in Python How to install Python in Windows How to install Python in Ubuntu How to install PIP in Python How to call a function in Python How to download Python How to comment multiple lines in Python How to create a file in Python How to create a list in Python How to declare array in Python How to clear screen in Python How to convert string to list in Python How to take multiple inputs in Python How to write a program in Python How to compare two strings in Python How to create a dictionary in Python How to create an array in Python How to update Python How to compare two lists in Python How to concatenate two strings in Python How to print pattern in Python How to check data type in python How to slice a list in python How to implement classifiers in Python How To Print Colored Text in Python How to develop a game in python How to print in same line in python How to create a class in python How to find square root in python How to import numy in python How to import pandas in python How to uninstall python How to upgrade PIP in python How to append a string in python How to open a file in python

Sorting

Python Sort List Sort Dictionary in Python Python sort() function Python Bubble Sort

Programs

Factorial Program in Python Prime Number Program in Python Fibonacci Series Program in Python Leap Year Program in Python Palindrome Program in Python Check Palindrome In Python Calculator Program in Python Armstrong Number Program in Python Python Program to add two numbers Anagram Program in Python Even Odd Program in Python GCD Program in Python Python Exit Program Python Program to check Leap Year Operator Overloading in Python Pointers in Python Python Not Equal Operator Raise Exception in Python Salary of Python Developers in India What is a Script in Python Singleton design pattern in python

Python List

The list is one of the most versatile, mutable data-structures in Python. It can store heterogeneous data or different types of data. The list contains comma-separated values (item) within the square brackets. Creating a list in Python is simple as follows:

list1 = [‘Abhay’,’Arjun’,’Himanshu’,’Anubhav’]
list2 = [1,2,3,4,5,6]
list3 = [‘Himanshu’,20, 54.6,’Abhay’, ’a’, ’b’] 

Indexing and Slicing in List

Indexing in List:

Indexing of list can be done by using [] operator.

list =[ 'P', 'Y' , 'T' , 'H' , 'O' ,N’]                                                                               

Python List

The values in the list can be accessed by its index position. The index starts from 0 to n-1. The first element is stored in the 0th index, and the second element is stored in the first index and so on.

The rightmost index position is -1, and its adjacent left index is -2 and so on. For example:

Python List 1

Slicing in List

Python provides a facility to get a sub-list of the list. Sometimes we require only some data from a given list then slicing makes it happen. The syntax is:

list_variable[start: end: step]
  • start refers to the starting position of the list element. 
  • stop refers to the index of the element where we should stop just before to finishing of our slice. 
  • step allows you to take each nth-element within a start:stop range.

Let's look at this concept using below example:

Example-1:

list = [10,20,30,40,50,60,70,80,90]
print(list[2:6])

Output:

[30, 40, 50, 60]

In the above example, the start is equal to 2, so slicing starts from the second position. The value at index 2 is 30.

The stop indicates the last element of the list, and its value is 60. Hence it will stop just before to the stop index.

The steps permit to take each nth-element within a start: stop range.

Python List 2

We can skip the start index and then it will starts from 0 by default. For example:

list = [10,20,30,40,50,60,70,80,90]
print(list[:4])

Output

[10, 20, 30, 40]

So, list[:4] is equivalent to the list[0:4]. It is a shortcut to extract first nth element 

We can skip the stop index also. It will return last n elements of the given list. For example:

list = [10,20,30,40,50,60,70,80,90]
print(list[4:])

Output

[50, 60, 70, 80, 90]

In the above example, we skip the stop index that’s mean it takes elements from the start position to end of the list.

Example-2:

list = [10,20,30,40,50,60,70,80,90]
print(list[::])
#By default step-size is
1. There is no need to specify it
print(list[::2])
# Here step-size is two 
print(list[1::3])
print(list[2:7:2])

Output:

[10, 20, 30, 40, 50, 60, 70, 80, 90]
[10, 30, 50, 70, 90] 
[20, 50, 80]
[30, 50, 70] 

In the above program, we can omit start and stop the argument and use only step argument. By providing step, we can skip some elements.

Accessing elements of list using negative indexing

list = [10,20,30,40,50,60,70,80,90]
print(list[-3:])
#The index position is
count from backward. start is -3 and it will proceed to last index of list
print(list[1:-1])
print(list[-5:-2])
# Here step-size is two
print(list[-3:])
print(list[1:-3:2])
print(list[:7:-2])
print(list[::-1])
# step-size is -1.it will
reverse entire list 

Output:

[70, 80, 90]
[20, 30, 40, 50, 60, 70, 80] 
[50, 60, 70]
[70, 80, 90]
[20, 40, 60]
[90]
 [90, 80, 70, 60, 50, 40, 30, 20, 10] 

Modification (update) in List

Lists are mutable; it means we can modify the elements of the list using the slice and assignment operator. The append() function of list is also used to add value in list.

list = [10,21,30,45,50,63,78,80,90]
list[0]=1
print(list)
list[1:4]=[2,3,4]
print(list)
list[2]= 'Himanshu'
print(list)
list[3:5]='abc'
print(list)

Output:

[1,21, 30, 45, 50, 63, 78, 80, 90]
[1, 2, 3, 4, 50, 63, 78, 80, 90]
[1, 2, 'Himanshu', 4, 50, 63, 78, 80, 90]
[1, 2, 'Himanshu', 'a', 'b', 'c', 63, 78, 80, 90] 

Deletion in List

The del keyword is used to delete the element of list. It is used when we know exactly which element needs to be deleted. The remove () or pop () method can also be used for deleting the element. For example:

list = [10,21,30,45,50,63,78,80,90]
del list[0]
print(list)
del list[1:4]
print(list)
del list[::2]
print(list)

Output:

[21,30, 45, 50, 63, 78, 80, 90]
[21, 63, 78, 80, 90]
[63, 80] 

We can also delete the entire list. As per the following example:

list = [10,21,30,45,50,63,78,80,90]
del list
#TypeError because list is deleted and we are accessing the first element
of list
print(list[0])

Output:

TypeError:'type' object is not subscriptable

Basic Operations in List

There are various operations in the list as follows.

  • Repetition

The repetition operator (*) is used to repeat list elements for multiple times.

list1 =[1,2,3,4,5]
print(list1*2)

Output:

[1, 2, 3, 4,5, 1, 2, 3, 4, 5]
  • Concatenation

The concatenation operator(+) is used to concatenate two or more list.

list1 =[1,2,3,4,5]
list2 =[6,7,8,9,10]
print(list1+list2)

Output:

[1,2, 3, 4, 5, 6, 7, 8, 9, 10]
  • Iteration

The list can be iterated using for loop

list1 =[1,2,3,4]
for i in list1:
print(i)

Output:

1
2
3
4
  • Membership

If a particular item exists in a particular list than It returns true otherwise false.

list1 =[1,2,3,4]
print(3 in list1) 

     Output:

True

Built-in functions in List

Sr. no. Functions Description
1. len(list) It is used to compute the length of list
2. cmp(list1, list2) It compares the elements of both the lists.
3. max(list) It returns the maximum element of the list.
4. min(list) It returns the minimum element of the list.
5. list(seq) It changes any sequence to the list.



ADVERTISEMENT
ADVERTISEMENT