Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
87 views

15.python Lists

The document provides an overview of Python lists. It discusses how to create lists, access elements within lists, perform common list operations like slicing and iteration. It also covers list comprehensions, multi-dimensional lists, adding and removing elements from lists, and built-in list methods. The document is intended to teach readers about the list data type in Python.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
87 views

15.python Lists

The document provides an overview of Python lists. It discusses how to create lists, access elements within lists, perform common list operations like slicing and iteration. It also covers list comprehensions, multi-dimensional lists, adding and removing elements from lists, and built-in list methods. The document is intended to teach readers about the list data type in Python.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 8

Courses

Free Courses Interview Questions Tutorials Community

Home /
Tutorial /
Python Lists

Python Lists
By Manoj 9.3 K Views 22  min read Updated on March 9, 2022

In this module of the Python tutorial, we will learn in detail about the list data type in Python. We will further learn how to create
lists, including multi-dimensional lists, how to access lists, and Python list comprehensions, and toward the end of this module
we will also learn about various operations in Python list data type.

Become a Certified Professional

Python Tutorial

Python Variables -
Constant, Global & Static
Variables

Numbers in Python

String in Python

Python Lists

Tuple in Python

Python Sets

Python Dictionary

Python Operators

Type conversion in
Python

Python If Else
Statements

Python While Loop

For Loop in Python

Python Functions -
Define & Call a Functions
in Python

Lambda Function in
Python

Python Built in
Functions with Examples

Python Arrays
Python Classes and
Objects

Python Modules

Python Dates

Python JSON

Python RegEx

PIP Python

Python File Handling -


How to Create, Open,
Read & Write

Exception Handling in
Python

Enumerate Function in

List in Python
Lists are Python’s most flexible ordered collection object type. It can also be referred to as a sequence that is an ordered
collection of objects that can host objects of any data type, such as Python Numbers, Python Strings, and nested lists as
well. Lists are one of the most used and versatile Python Data Types. In this module, we will learn all about lists in order to
get started with them.

Following is the list of all topics that are going to be covered in this module.

Creating_Lists_in_Python
Creating Multi-dimensional Lists in Python
Python List Comprehension
Python Lists Extension
Accessing Lists in Python
Length of List in Python
Linked List in Python
List to String in Python
Common_List_Operations_in_Python

Slicing Python Lists


Iterating through Python Lists
Update or Add Elements in a Python List
Remove elements from list in python
Remove duplicates from lists in python
Sorting Lists in Python
Reverse a list in python

Python List Functions and Methods

Without any further ado, let’s get started.

Creating a Lists in python


A list can be created by putting the value inside the square bracket, and values are separated by commas.

List_name = [value1, value2, …, value n]

Unlike strings, lists can contain any sort of object: numbers, strings, and even other lists. Python lists are:
Ordered collections of arbitrary objects
Accessed by offset
Arrays of object references
Of variable length, heterogeneous, and arbitrarily nestable
Of the category, mutable sequence
Data types in which elements are stored in the index basis with starting index as 0
Enclosed between square brackets ‘[]’

Example:

list1 = [1,2,3,4,5]

list2 = [“hello”, “intellipaat”]

Go for this in-depth job-oriented Python Training in Hyderabad now!

Creating Multi-dimensional Lists in Python


A list can hold other lists as well which can result in multi-dimensional lists, also called a List of Lists. Next, we will see how
to create a python list of lists.

One-dimensional Lists in Python:


init_list = [0]*3

print(init_list)

Output:

[0, 0, 0]

 Two-dimensional Lists In Python:


two_dim_list = [ [0]*3 ] *3

print(two_dim_list)

Output:

[[0, 0, 0], [0, 0, 0], [0, 0, 0]]

Three-dimensional Lists in Python:


two_dim_list = [[ [0]*3 ] *3]*3

print(two_dim_list)

Output:

[[[0, 0, 0], [0, 0, 0], [0, 0, 0]],

[[0, 0, 0], [0, 0, 0], [0, 0, 0]],

[[0, 0, 0], [0, 0, 0], [0, 0, 0]]]

Python List Comprehension


Python List comprehension helps in constructing lists in a completely natural and easy way.

List = [1,2,3,4,5]

List1 = [ i for i in range(5)]

print(List1)

Output:

[0, 1, 2, 3, 4]

Complicated Python List Comprehension Examples


Example 1:
print ([a+b for a in ‘mug’ for b in ‘lid’])

Output:

[‘ml’, ‘mi’, ‘md’, ‘ul’, ‘ui’, ‘ud’, ‘gl’, ‘gi’, ‘gd’]

Example 2:

list_fruit = [“Apple”,”Mango”,”Banana”,”Avocado”]

first_letters = [ fruits[0] for fruits in list_fruit ]

print(first_letters)

Output:

[‘A’, ‘M’, ‘B’, ‘A’]

We have the perfect professional Python Course in Bangalore for you!

List Extension
Python allows lists to resize in many ways. We can do that just by adding two or more of them.

Example:

two_dim = [[0]*3 for i in range(3)]print(two_dim)

[[0, 0, 0], [0, 0, 0], [0, 0, 0]]

two_dim[0][2] = 1

print(two_dim)

Output:

[[0, 0, 1], [0, 0, 0], [0, 0, 0]]

extend(): 

Alternately, we can do extension by using the extend() method. See the following example:

L1 = [‘a’, ‘b’]

L2 = [‘c’, ‘d’]

L1.extend(L2)

print(L1)

Output:

[‘a’, ‘b’, ‘c’, ‘d’]

Learn more about Lists from our blog on Python List Comprehension.

append(): 

Next, we can append a value to a list by calling the append() method. See the following example:

L1 = [‘a’, ‘b’]

L2 = [‘c’, ‘d’]

L1.extend(L2)

print(L1)

Output:

[‘a’, ‘b’, ‘c’, ‘d’]

Accessing Lists in Python


Much similar to strings, we can use the index number to access items in lists as shown below.

Example:

list1 = [1,2,3,4,5]

Accessing a List Using Reverse Indexing


To access a list in reverse order, we have to use indexing from −1, −2…. Here, −1 represents the last item in the list.
print(list1[-1])

print(list1[-3])

Output:

Length of List
In python, there is a built-in method called, len() that helps you get the number of items in a list. It can also be used for
arrays, tuples, dictionaries etc. The function takes a list as the argument and returns its length.

List1 = [“Intellipaat”, “Python”, “Tutorial”, 1, 2, 3]

print(“The number of items in this list is ”, len(List1))

The output will be 6

Linked list in Python


A linked list is an ordered collection of objects. The data elements in a linked list are connected to each other via links, and
this makes them different from normal lists. They store elements in memory. Normal lists use contiguous memory blocks
to store data references, whereas linked lists store the references as a part of their own elements

Python does not have linked lists in its standard library so it is implemented using the concept of nodes.

Each of the data elements is connected to other data elements using pointers. Linked lists contain a link element called
first. Each link carries two fields, a data field and a link field called next, which links each element to the next element. The
last link carries a null link, marking that it is the end of the linked list.

The types of linked lists are – 

Singly Linked List − Item navigation is forward only.


Doubly Linked List − Items can be navigated in both directions, forward and backward.
Circular Linked List − The last item has the link of the first element as next and the first element has the link to the last
element as previous.

Check out how Intellipaat is helping people get Python training in the easiest way. And also, we are providing trainees
with a free guide to all Python interview questions.

List to String
A list can be converted to a string using the join() method.

def ListToString(a):

s1 = “ ”

return(s1.join(a))

a = [‘Intellipaat’,‘Python’,‘tutorial’]

print(ListToString(a)

Common List Operations in Python


Following is the list of some of the most common list operations in Python, along with their descriptions and examples.

Slicing Python Lists


Slicing operation is used to print a list up to a specific range. We can use slice operation by including the starting index and
ending index of the range that we want to print separated by a colon as shown below:

list1[2:4]

output:

[3, 4]

list1[2:-1]

output:

[3, 4]

list1[:2]

output:

[1, 2]

Looking for Data Science with Python training All-in-1 Combo Training? Enroll now!

Iterating through Python Lists


Iterating is quite simple in lists. We can just use Python for loop to iterate, as shown below:

list1 = [1,2,3,4,5]

for element in list1:

print(element)

Output:

List comprehension in Python


List comprehension has a shorter syntax to create a new list, based upon the values of a preexisting list.

Example: If you have a list of programming languages, and based on that, you have to create a new list, containing just the
languages with the letter ‘a’ in their name. Without list comprehension, you would need to write a for statement with the
condition inside, whereas, using list comprehension, all that can be done with just one line of code:

languages = [“python”, “java”, “c”, “javascript”, “kotlin”]

newlist = [x for x in languages if “a” in x]

print(newlist) 

The output will be [‘java’,’javascript’]

Update or Add Elements in a Python List


We can update a particular item or multiple items of a list by using the slice operation, and then add an element using the
append () method as shown below.

Example:

list1[4] = ‘number’print(list1)list1[4:7] = [“Apple”,”Mango”,”Banana”]

print(list1)list1.insert(0,33)

print(list1)list1.insert(6,29)

print(list1)

Output:

[1, 2, 3, 4, ‘number’]

[1, 2, 3, 4, ‘Apple’, ‘Mango’, ‘Banana’]

[33, 1, 2, 3, 4, ‘Apple’, ‘Mango’, ‘Banana’]

[33, 1, 2, 3, 4, ‘Apple’, 29, ‘Mango’, ‘Banana’]

Remove elements from the list in python


There are three ways of removing elements from lists. We can either use the del keyword to remove a particular element or
we can use the remove () method, and the last way is using the pop () method, as shown in the following code block:

list1 = [1,2,3,4,5]

del list1[2]

list2 = [1,2,3,4,5]

list2.remove(4)

print(list2)

list3 = [1,2,3,4,5]

print(list3.pop(1))

print(list3)

Output:

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

[1, 3, 4, 5]

Remove duplicates from lists in python


Here’s an example of the list where some items are repeated. Let us see how we can remove duplicates from the list in
python.

mylist = ["a", "b", "c", "d", "c"]

mylist = list(dict.fromkeys(mylist))

output:

[“a”, “b”,”c”,”d”]

Reverse a list in python


lst = [10, 11, 12, 13, 14, 15]

lst.reverse()

print(lst)

output:

[15, 14, 13, 12, 11, 10]

Enroll yourself in Online Python Training in Sydney and give a head-start to your career in Python Programming!

Sorting Lists in Python


Python list implements the sort() method for ordering (in both ascending and descending order) its elements in place.

list1.sort()

Sorting in ascending order:

list1 = [1,3,2,4,5,9,6]

list1.sort()

print(list1)

output:

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

Sorting in descending order:

list1 = [1,3,2,4,5,9,6]

list1.sort(reverse=True)

print(list1)

output:

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

Python List Functions and Methods


Let’s understand different types of Python functions for lists through the following table that contains a list of different
functions with their respective descriptions.

Method Description

min(list_name) Returns the minimum value from a list in Python

max(list_name) Returns the largest value from a list in Python

len(list_name) Returns the number of elements in a list in Python

cmp(list1,list2) Compares two lists in Python

list.reverse() Reverses a list in Python

list.sort Sorts a list in Python

list(sequence) Converts the sequence of a list in Python

list.append(value) Adds a value into a list in Python

list.remove(value) Removes a value from a list in Python

With this, we come to the end of this module in Python Tutorial. Now, if you’re interested to know why Python is the most
preferred language for Data Science, you can go through this Python Data Science tutorial.


Previous Next

Course Schedule

You might also like