Lists concepts in Python

The list is a type of sequence available in Python. Lists in Python are the most versatile elements. They do not need to be homogeneous, which means, the items do not need to be of the same type. In Python, the elements are written in square brackets and are separated by the commas.

Lists in Python are like data containers that can store multiple data at the same time. They need to be ordered and with a definite count. Every element in the lists in Python has a definite place, hence the elements can be duplicated with each element having a distinct place and credibility.

If you want enrich your career and become a professional in python, then visit Mindmajix - a global online training platform : "python online training"   This course will help you to achieve excellence in this domain

 

 

Creation Of List In Python 

The creation of the lists in Python is very easy. The sequence needs to be placed in the square brackets and they do not require built-in function which is necessary in case of a list. As mentioned before, the elements can be duplicated in the lists of Python.

Lists are mutable, i.e., their elements can be mutated or edited.

Now, we will have a look at various examples of the list.

Example with a single string:

List = ['Element']
print("List with the use of String: ")
print(List)
Here, we will print a single string element.

Example with a single string:

 

Output:

List with the use of String:
['Element']

List with multiple elements:

List = ["Mars", "Moon", "Earth"]
print("Planets: ")
print(List[0]) 
print(List[2])

Here, multiple specific elements will be printed:

Output:

Planets:
Mars
Earth

List with the use of duplicate numbers:

List = [1, 2, 4, 4, 3, 3, 6, 5]
print("List with the use of duplicate Numbers: ")
print(List)

Here, the list with the duplicate number will be printed.

Output:

List with the use of duplicate Numbers:

[1, 2, 4, 4, 3, 3, 6, 5]

List with the mixed values:

List = [1, 2, 'Keyboard', 4, 'Mouse', 6, 'Computer']
print("List with the use of Mixed Values: ")
print(List)

Here, we will create a list with mixed values.

Output:

List with the use of Mixed Values:

[1, 2, 'Keyboard', 4, 'Mouse', 6, 'Computer']

MindMajix YouTube Channel

How to access elements from a list?

After having a list with a large number of elements, it is necessary to access only the desired elements. Here, we will access elements from a list. There are two ways of accessing the elements from the list:

  • List Index.
  • Negative Indexing.

List Index

For accessing the required elements from the list, one needs to specify the python list index number of the required element along with the ‘index  operator([])’. The python list index is required to be an integer. Here is an example of accessing the required elements from the list.

Code:

List = [1, 2, 'Keyboard', 4, 'Mouse', 6, 'Computer']
print("List with the use of Mixed Values: ")
print(List)

Here, in this code, we want to access the required list of elements, i.e., the planets. We have used the python list index number of the various elements to extract the required result.

Output:

Planets:
Mars
Earth
Jupiter

Negative Indexing

Negative Indexing is also possible in Python. For negative indexing, the negative sign is placed ahead of the index number of the element.

For example: [-1] refers to the first element from the last. One can access the elements from the end of the list rather than the beginning.

List = ["Mars", "Moon", "Earth", "Jupiter", "Titan"]
print("Negative Indexing:")
print(List[-1]) 
print(List[-3])

Output:

Negative Indexing:
Titan
Earth

 

How to slice the lists in Python?

Since we already know that we can print the desired elements from the list, Python allows us to print the specific range of elements from the list.

The python list ‘Slice’ operation is used to print a specific range of elements; it is denoted by the ‘Colon (:)’.To print the elements from a specific range, use the start index tag (:index) to specify the last range element until which you want to specify (index:).

This can be explained better with an example:

Code:

List = ['C', 'O', 'D', 'E', 'O', 'F', 'P', '3']
print(List[3:7])

Here, we are specifying the range of the elements from which we require the elements to be printed.

Output:

['E', 'O', 'F', 'P']

Multiple ranges of the elements can also be selected using the ‘python list slice’ operation multiple times.

Here is an example:

Code:

List = ['C', 'O', 'D', 'E', 'O', 'F', 'P', '3']
print(List[0:3])
print(List[5:7])

Here, we have specified multiple ranges of elements that we need to access.

Output:

['C', 'O', 'D']
['F', 'P']

Checkout Python Tutorials

How to change or add the elements to the list?

Unlike the strings and tuples in Python3, Lists are mutable, i.e., the elements can be added or the list can also be edited. The assignment operator (=) can be used to change an item or the range of items.

Code:

List = ['C', 'O', 'D', 'E', 'O', 'F', 'P', '3']
List[3:6] = ['I', 'N', 'G']
print(List)

We will be replacing some of the components of the python list function with others.

Output:

['C', 'O', 'D', 'I', 'N', 'G', 'P', '3']

As you can see above, the items of the list have been replaced with other components.

Item or a list of Items can be added to the list. One item can be added using the ‘append()’ method and several items can be added using the ‘extend()’ method.

Code:

List = ['C', 'O', 'D', 'E', 'O', 'F', 'P', '3']
List.append('L')
print(List)

In this code, we will add single element ‘L’ to the list using the python list append method.

Output:

['C', 'O', 'D', 'E', 'O', 'F', 'P', '3', 'L']

As you can see, the element ‘L’ has been added to the ‘python list function’.

Code:

List = ['C', 'O', 'D', 'E', 'O', 'F', 'P', '3']
List.extend(['L', 'A', 'N'])
print(List)

In this code, we will add multiple elements in the list using the extend method.

Output:

['C', 'O', 'D', 'E', 'O', 'F', 'P', '3', 'L', 'A', 'N']

How to delete or remove the elements from the list?

Python allows us to delete multiple elements from the list. It is done using ‘del’ function. First, we will delete a single function from the list.

Code:

List = ['C', 'O', 'D', 'E', 'O', 'F', 'P', '3']
del List[7]
print(List)

In this code, we will be deleting element with the index ‘7’ that is element ‘3’.

Output:

['C', 'O', 'D', 'E', 'O', 'F', 'P']

As you can see, the element ‘3’ has been removed.

Python List Methods

There are various methods that can be performed on the Lists. The methods are written as ‘list.method()’ where the name of the list is the ‘list’ and method will be replaced by the function that we will want to use on our list.

MethodDescription
append()Adding an element at the end of the list.
extend()Adding a number of elements at the end of the list.
insert()Used to insert the item at some definite index.
remove()Removes a certain element from the list.
pop()Removes a certain element and returns it to the user at certain index.
clear()Removes all the elements from the list.
index()Returns the index of the first item which matches the value of the method.
count()Returns the count of the number of items passed as argument.
sort()Sort the items of the list in the ascending order.
reverse()Reverses the order of items of the list.

List comprehension

List comprehension is a useful way of creating a list from an already existing list.
In list comprehensions, one has to specify the expression with the ‘for’ statements in the square brackets.

[Related Article: Regular expression operations]

Code:

list = [3 * x for x in range(5)]
print(list)

Result:

[0, 3, 6, 9, 12]

Frequently Asked Python Interview Questions & Answers

Other List Operations in Python

List membership test

It is also possible to check if a certain element belongs to the list or not. It can be done using the ‘in’ keyword.

Code:

TheList = ['C', 'O', 'D', 'E', 'O', 'F', 'P', '3']
print('O' in TheList)

Now, we will be finding if the ‘O’ is present in the list ‘TheList’. Since it is present in the list, we will get the result ‘True’.

Output:

True

It is also possible to check the other way round if we want to see that if the particular element is NOT present in the list or not. The keyword used for this process is ‘not in’.

Code:

TheList = ['C', 'O', 'D', 'E', 'O', 'F', 'P', '3']
print('O' not in TheList)

Result:

Since the element ‘O’ is present in the list, the output must be false.

False

  • Iterating through a list

It is also possible to iterate the elements of a list. It can be done using the ‘for’ loop.

Code:

In this code, we will iterate each item of the list.
forlang in ['HTML','Ruby','Python']:
print("I want to learn", lang)

Output:

I want to learn HTML
I want to learn Ruby
I want to learn Python

  • Built-in Functions with lists

Some built-in functions can be used to perform various tasks:

FunctionDescription
sum()It returns the sum of all the elements of the list.
max()It returns the largest items of the list.
min()It returns the smallest items of the list.
len()It returns the number of items present in the list.
all()Returns True if all the items of the list are true or if the list is empty.
any()It returns true if any element of the list is true and returns false if the list is empty.

Python List Comprehensions versus Generator Expressions

Here are the differences between Python list comprehensions and Generator expressions:

Python List ComprehensionsGenerator Expressions
It is possible to create lists using the ‘for’ loop and the less amount of code.Generator Expression only generates items which we require rather than creating the whole list at once.
For List comprehensions, Python reserves the memory for the entire list.Generator Expressions only generate the element which is in demand.
List comprehensions are not memory efficient.Generator expressions are memory efficient.

If you are interested learn python and build a career in it ? Then checkout our python training near your cities

Python Training ChennaiPython Training New YorkPython Training in BangalorePython Training in Dallas

These courses are incorporated with Live instructor-led training, Industry Use cases, and hands-on live projects. This training program will make you an expert in Microsoft Azure and help you to achieve your dream job.

 

 

explore Python Sample Resumes! Download & Edit, Get Noticed by Top Employers!Download Now!
Course Schedule
NameDates
Python TrainingOct 15 to Oct 30View Details
Python TrainingOct 19 to Nov 03View Details
Python TrainingOct 22 to Nov 06View Details
Python TrainingOct 26 to Nov 10View Details
Last updated: 03 Apr 2023
About Author

Anjaneyulu Naini is working as a Content contributor for Mindmajix. He has a great understanding of today’s technology and statistical analysis environment, which includes key aspects such as analysis of variance and software,. He is well aware of various technologies such as Python, Artificial Intelligence, Oracle, Business Intelligence, Altrex, etc. Connect with him on LinkedIn and Twitter.

read less
  1. Share:
Python Articles