×

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

Handling missing keys in Python dictionaries

In this lesson, you will discover how to create a Python application that will manage missing keys in a dictionary. Python dictionaries store data as key-value pairs, where each value...

3 minutes read.

Python maketrans() function

Introduction A static method is the string maketrans() one. It is used to make a one-to-one mapping between a string's character and its translation, i.e., to define the list of characters...

5 minutes read.

Python Percentage Sign

In Python, the percentage sign significantly completes two things. They are: It goes about as a Modulo administrator. It helps in string organizing. Allow us to see every one of them plainly. Modulo operator: Like...

2 minutes read.

Programs for Printing Pyramid Patterns in Python

<!-- wp:paragraph --><p>Python supports printing patterns using basic for loops. The number of rows is handled by the first outer loop, while the number of columns is handled by the...

9 minutes read.

Sort a dataframe based on a column in Python

Sorting the dataframe based on a column requires pandas which is An open-source library called Python Pandas is described as offering high-performance data processing in Python. For both professionals and...

4 minutes read.

Python MySQL Database Connection

In this article, you will be able to understand how to connect to a MySQL database through Python. We generally can use many methods or modules to connect to the database...

6 minutes read.

Traverse Dictionary in Python

Traversing a dictionary is visiting each and every step in the dictionary, which is also called iterating the dictionary In Python, dictionaries are a useful and commonly used data structure in...

3 minutes read.

Python Logical Operators

In python, there are many operators which we use in our program. Operators are used in manipulating a particular value or operand. Logical operators are used mainly to evaluate an...

7 minutes read.

Python Program to Find the gcd of Two Numbers

Introduction Greatest Common Divisor is the full form of gcd. The greatest common divisor, or GCD, of two numbers, is a value that can exactly divide the two digits and is...

5 minutes read.

Python Tuple count() Method

Python Tuple count() Method The tuple.count() method in Python returns the number of times a specified value appears in the tuple. Syntax tuple.count(value) Parameter value- This parameter represents the element to search in the tuple Return This...

1 minute read.

Read numpy array in Python

Numpy is a numerical python that deals with multidimensional arrays mostly used in storing multiple values. Python's core scientific computing package is called NumPy. This Python library provides multidimensional array...

9 minutes read.

Cube Root in Python

In general, the cube is a three-dimensional solid figure that has 6 square faces. It is also called a geometrical shape with six equal faces, eight vertices, and twelve edges....

3 minutes read.

Installing Packages in Python

It's critical to understand that the term "package" here refers to a collection of software that must be installed (i.e. as a synonym for a distribution). It has nothing to...

6 minutes read.

Python List reverse() method

 Python List reverse() method The list.reverse () method in Python reverses the elements of the list in place. Syntax list.reverse() Parameter NA Example 1 # Python program explaining # the list.reverse() method weekList = ['Sun','Thurs','Mon','Fri', 'Tues', 'Wed'] print("Actual week list: ",weekList) #...

1 minute read.

Python Program to find the length of a string

Python program to find the length of a string A string in Python is a set of Unicode characters. It can't be changed once it's been declared. The number of characters...

2 minutes read.

Python MongoDB Tutorial

An Introduction to MongoDB MongoDB is a document-oriented database application. It is an Open-source and platform-independent program. MongoDB is similar to few NoSQL databases that store the data in the documents...

17 minutes read.

Global variables in python

In Python, considering the scope, variables are categorized into global and local variables. In this article, we will discuss these two types along with examples. Any variable holds a value in...

4 minutes read.

Periodogram in Python

Python:  Python programming language is one of the most used programming languages, as it is used widely in the field of software and data analysis, web development, etc. It is said...

3 minutes read.

Bar Plot in Python

A bar chart or bar graph displays categorical data using rectangular bars with heights or lengths proportionate to the values for the data distributed in the dataset. In a bar...

16 minutes read.

Import py file in Python

In Python programming language, a module is a single layer of block of Python code that can be loaded and used by importing into other Python block of code. A module...

4 minutes read.