×

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.

Related Topics

Python Matrix Operations

Python Matrix In this section of the Python tutorial, we will look at the introduction of the matrix in Python programming. We will perform many operations on the Python matrix using...

21 minutes read.

Python list() | List class in Python

The list() class in Python creates a list object where the list object is a collection which is ordered and changeable. Syntax class list([iterable]) Parameter Iterable: It is a required parameter which represents a sequence, collection...

1 minute read.

How to Install Pandas in Python?

Pandas is a library created in Python for handling and analyzing data. Pandas provides a variety of procedures and data structures for manipulating time series and numerical data.  Pandas is...

3 minutes read.

Difference between Perl and Python

Control and presently utilized for a great many undertakings, including framework organization, web improvement, network programming, and GUI improvement, and the sky is the limit from there. About Perl? Perl is a...

4 minutes read.

Python ltrim() function

Python ltrim() function The ltrim() function in PHP removes whitespace or other predefined characters from the beginning or left side of a string. The related functions are as follows: rtrim() – This function is used to...

1 minute read.

Python Os sep

Python: Python is an interactive and more accessible language than any other programming language. The python programming language uses a variety of libraries to perform the operations in a faster way....

3 minutes read.

How to Take Input in Python

How To Take Input In Python Python has various in-built functions that help in code redundancy. Let's discuss the usage of some functions- ascii() – it returns a readable representation of objects.format()...

4 minutes read.

Anonymous/Lambda Function in Python

Lambda keyword is used to declare an Anonymous function, i.e. a function that does not have any name. It is also called Anonymous functions. In python, normal functions are defined...

3 minutes read.

Continue and Pass Statements in Python

Difference between continue and pass statements in Python The tasks can be repeated and automated efficiently using loops in Python. Sometimes we have to exit from the entire loop completely, we...

2 minutes read.

How to develop a game in python

Fun always makes a task interesting and easy to execute. Learning in the same theoretical way at some point reaches the boring spot. In this article, using some Python knowledge,...

13 minutes read.

How to upgrade PIP in python

We use the PIP command in our command prompt to install any package. PIP is used to install published Python packages in the PyPI (Python package index) or other indices....

3 minutes read.

Python Dictionary items() method

Python Dictionary items() method The dictionary.items() method in Python returns a view object that displays a list of dictionary's (key, value) tuple pairs. Syntax dictionary.items() Parameter NA Return This method returns a view object, displaying the list...

1 minute read.

Python oct() function

Python oct() function The oct() function in Python converts an integer number to an octal string prefixed with “0o”. Syntax oct(x) Parameter x: This parameter represents an Integer Number Return This function returns an octal string. Example 1 #...

1 minute read.

Reverse a String in Python

Python is an object-oriented high-level programming language. Python has dynamic semantics and has high-level built-in data structures which support dynamic typing and dynamic binding. Python provides rapid development. It has...

4 minutes read.

Best Database in Python

In this tutorial, Firstly, we will understand what the term database means. Further, we will see the various databases supported in Python and when to use which one. Further, we...

7 minutes read.

Python And Operator

Python's and operator takes two operands that can be either object, Boolean expressions, or both. And operator creates more complex expressions using those operands. Conditions are the common name for...

8 minutes read.

Program of Cumulative Sum in Python

Introduction This tutorial, explains what is meant by lists, the cumulative total, several approaches to calculating the cumulative sum of digits in a list, etc. Learn the straightforward Python codes for...

5 minutes read.

__init__ in python

Every programmer will enclose to object-oriented programming (OOP) these days. As we know, that python is the latest and most modern programming language; python supports to implementation of object-oriented philosophy....

5 minutes read.

Insertion Sort using Python

Insertion sort is a type of sorting technique that is used for sorting an array with random elements. Using sorting methods, any unsorted array can be sorted into ascending or...

3 minutes read.

Python ord() Function

Python ord() Function The ord() function in Python returns the number representing the Unicode code of a specified character. Syntax ord(c) Parameter c: This parameter represents a string or any character. Return This function returns the number...

1 minute read.