0% found this document useful (0 votes)
8 views15 pages

List Comprehension

The document provides an introduction to Python lists, explaining their characteristics, creation, and various methods for accessing and manipulating list elements. It covers topics such as negative indexing, list size, adding elements with append and insert methods, and removing elements using del, remove, and pop methods. Examples are provided to illustrate each concept, making it a comprehensive guide for understanding Python lists.

Uploaded by

rohit
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views15 pages

List Comprehension

The document provides an introduction to Python lists, explaining their characteristics, creation, and various methods for accessing and manipulating list elements. It covers topics such as negative indexing, list size, adding elements with append and insert methods, and removing elements using del, remove, and pop methods. Examples are provided to illustrate each concept, making it a comprehensive guide for understanding Python lists.

Uploaded by

rohit
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 15

3/24/23, 8:37 PM Practice | GeeksforGeeks | A computer science portal for geeks

List Introduction

kPython Lists are just like dynamically sized arrays, declared in other languages
(vector in C++ and ArrayList in Java). In simple language, a list is a collection of
things, enclosed in [ ] and separated by commas.

The list is a sequence data type which is used to store the collection of
data. Tuples and String are other types of sequence data types.

Example of a list in python:


Here we are creating Python List using [].

Python3

Var = ["Geeks", "for", "Geeks"]


print(Var)

Output

['Geeks', 'for', 'Geeks']

Lists are the simplest containers that are an integral part of the Python language.
Lists need not be homogeneous always which makes it the most powerful tool in
Python. A single list may contain DataTypes like Integers, Strings, as well as
Objects. Lists are mutable, and hence, they can be altered even after their
creation.

Creating a List in Python


Lists in Python can be created by just placing the sequence inside the square
brackets[]. Unlike Sets, a list doesn’t need a built-in function for the creation of a
list.
Articles Read  Prev
0 of 6 Complete. (0%)
Next 

https://practice.geeksforgeeks.org/batch/Datasci-4/track/da-python-data-structure/article/Njc2Mg%3D%3D 1/15
3/24/23, 8:37 PM Practice | GeeksforGeeks | A computer science portal for geeks
Dash
Note: Unlike Sets, the list may contain mutable elements.

Articles
Example:

Python3
Videos

# Python program to demonstrate


Problems
# Creation of List

# Creating a List
Quiz
List = []
print("Blank List: ")
print(List)

# Creating a List of numbers


List = [10, 20, 14]
print("\nList of numbers: ")
print(List)

# Creating a List of strings and accessing


# using index
List = ["Geeks", "For", "Geeks"]
print("\nList Items: ")
print(List[0])
print(List[2])

Output

Blank List:
[]

List of numbers:
[10, 20, 14]

List Items:
Menu Geeks
Geeks

Articles Read 
0 of 6 Complete. (0%)


https://practice.geeksforgeeks.org/batch/Datasci-4/track/da-python-data-structure/article/Njc2Mg%3D%3D 2/15
3/24/23, 8:37 PM Practice | GeeksforGeeks | A computer science portal for geeks
Dash
Accessing elements from the List
In order to access the list items refer to the index number. Use the index operator [ ]
to access an item in a list. The index mustArticles
be an integer. Nested lists are accessed
using nested indexing.
Example 1: Accessing elements from listVideos

Python3
Problems

# Python program to demonstrate


# accessing of element from list Quiz

# Creating a List with


# the use of multiple values
List = ["Geeks", "For", "Geeks"]

# accessing a element from the


# list using index number
print("Accessing a element from the list")
print(List[0])
print(List[2])

Output

Accessing a element from the list


Geeks
Geeks

Example 2: Accessing elements from a multi-dimensional list

Python3

# Creating a Multi-Dimensional List


Menu
# (By Nesting a list inside a List)
List = [['Geeks', 'For'], ['Geeks']]

Articles Read 
# accessing
(0%) an element from the
0 of 6 Complete. 
# Multi-Dimensional List using 

https://practice.geeksforgeeks.org/batch/Datasci-4/track/da-python-data-structure/article/Njc2Mg%3D%3D 3/15
3/24/23, 8:37 PM Practice | GeeksforGeeks | A computer science portal for geeks

# index number Dash

print("Accessing a element from a Multi-Dimensional list")


print(List[0][1])
Articles
print(List[1][0])

Videos
Output

Accessing a element from a Multi-Dimensional list


For Problems
Geeks

Quiz

Negative indexing
In Python, negative sequence indexes represent positions from the end of the array.
Instead of having to compute the offset as in List[len(List)-3], it is enough to just
write List[-3]. Negative indexing means beginning from the end, -1 refers to the last
item, -2 refers to the second-last item, etc.

Python3

List = [1, 2, 'Geeks', 4, 'For', 6, 'Geeks']

# accessing an element using


# negative indexing
print("Accessing element using negative indexing")

# print the last element of list


print(List[-1])

# print the third last element of list


print(List[-3])

Output
Menu
Accessing element using negative indexing
Geeks
For
Articles Read 
0 of 6 Complete. (0%)


https://practice.geeksforgeeks.org/batch/Datasci-4/track/da-python-data-structure/article/Njc2Mg%3D%3D 4/15
3/24/23, 8:37 PM Practice | GeeksforGeeks | A computer science portal for geeks
Dash
Getting the size of the Python list
Python len() is used to get the length of the list.
Articles

Python3
Videos

# Creating a List
List1 = []
Problems
print(len(List1))

# Creating a List of numbers


Quiz
List2 = [10, 20, 14]
print(len(List2))

Output

0
3

Adding Elements to a Python List

Using append() method:

Elements can be added to the List by using the built-in append() function. Only one
element at a time can be added to the list by using the append() method, for the
addition of multiple elements with the append() method, loops are used. Tuples
can also be added to the list with the use of the append method because tuples
are immutable. Unlike Sets, Lists can also be added to the existing list with the use
of the append() method.
Example:

Python3

Menu
# Python program to demonstrate
# Addition of elements in a List

Articles Read 
0 of 6 Complete. (0%) a List
# Creating


https://practice.geeksforgeeks.org/batch/Datasci-4/track/da-python-data-structure/article/Njc2Mg%3D%3D 5/15
3/24/23, 8:37 PM Practice | GeeksforGeeks | A computer science portal for geeks

List = [] Dash

print("Initial blank List: ")


print(List)
Articles

# Addition of Elements
# in the List
Videos
List.append(1)
List.append(2)
List.append(4)
Problems
print("\nList after Addition of Three elements: ")
print(List)

Quiz
# Adding elements to the List
# using Iterator
for i in range(1, 4):
List.append(i)
print("\nList after Addition of elements from 1-3: ")
print(List)

# Adding Tuples to the List


List.append((5, 6))
print("\nList after Addition of a Tuple: ")
print(List)

# Addition of List to a List


List2 = ['For', 'Geeks']
List.append(List2)
print("\nList after Addition of a List: ")
print(List)

Output

Initial blank List:


[]

List after Addition of Three elements:


[1, 2, 4]
Menu
List after Addition of elements from 1-3:
[1, 2, 4, 1, 2, 3]

Articles Read 
List after Addition of a Tuple:
0 of 6 Complete. (0%)
[1, 2, 4, 1, 2, 3, (5, 6)] 

https://practice.geeksforgeeks.org/batch/Datasci-4/track/da-python-data-structure/article/Njc2Mg%3D%3D 6/15
3/24/23, 8:37 PM Practice | GeeksforGeeks | A computer science portal for geeks
Dash
List after Addition of a List:
[1, 2, 4, 1, 2, 3, (5, 6), ['For', 'Geeks']]
Articles

Using insert() method: Videos


Python List insert() method inserts a given element at a given index in a list using
Python.
Problems
Syntax:

Syntax: list_name.insert(index, element)


Quiz

Parameters:
index: the index at which the element has to be inserted.
element: the element to be inserted in the list.
Returns: Does not return any value.

Example 1: Python insert() method with string in Python.

Python3

lis = ['Geeks', 'Geeks']


lis.insert(1, "For")
print(lis)

Problems
Output
Courses
['Geeks', 'For', 'Geeks']

Get Hired
 2249  
Example 2: Inserting an Element into the List
Scholarship
Contests 

MenuHere, we are inserting 10 at the 5th position(4th index) in a Python list.


 POTDPython3

Articles Read 
0 of 6 Complete. (0%)


https://practice.geeksforgeeks.org/batch/Datasci-4/track/da-python-data-structure/article/Njc2Mg%3D%3D 7/15
3/24/23, 8:37 PM Practice | GeeksforGeeks | A computer science portal for geeks
Dash

list1 = [ 1, 2, 3, 4, 5, 6, 7 ]
Articles

# insert 10 at 4th index


list1.insert(4, 10)
Videos
print(list1)

Problems
Output

[1, 2, 3, 4, 10, 5, 6, 7]
Quiz

count() method
Python List count() method returns the count of how many times a given object
occurs in a List.
Syntax:

Syntax: list_name.count(object)
Parameters:
object: is the item whose count is to be returned.
Returns: Returns the count of how many times object occurs in the list.
Exception:
TypeError: Raises TypeError If more than 1 parameter is passed
in count() method.

Example:

Menu Python3

list2 = ['a', 'a', 'a', 'b', 'b', 'a', 'c', 'b']


Articles Read print(list2.count('b')) 
0 of 6 Complete. (0%)


https://practice.geeksforgeeks.org/batch/Datasci-4/track/da-python-data-structure/article/Njc2Mg%3D%3D 8/15
3/24/23, 8:37 PM Practice | GeeksforGeeks | A computer science portal for geeks
Dash

Output

3 Articles

Videos

del keyword
In python del is a keyword and remove(), pop() are in-built methods. The purpose
Problems
of these three are the same but the behavior is different remove() method delete
values or object from the list using value and the del and pop() deletes values or
object from the list using an index.The del
Quizkeyword deletes any variable, or list of
values from a list.
Syntax:

del list_name[index] # To delete single value


del list_name # To delete whole list

Example:

Python3

# program to demonstrate use of del keyword

# assign list
numbers = [1, 2, 3, 2, 3, 4, 5]

# use del
del numbers[2]

# display list
print(numbers)

# use del
del numbers[-1]

Menu # display list


print(numbers)

Articles Read 
# use del
0 of 6 Complete. (0%)
del numbers[0] 

https://practice.geeksforgeeks.org/batch/Datasci-4/track/da-python-data-structure/article/Njc2Mg%3D%3D 9/15
3/24/23, 8:37 PM Practice | GeeksforGeeks | A computer science portal for geeks
Dash

# display list
print(numbers)
Articles

Output
Videos
[1, 2, 2, 3, 4, 5]
[1, 2, 2, 3, 4]
[2, 2, 3, 4] Problems

Quiz

remove() method
The remove() method removes the first matching value from the list.
Syntax:

list_name.remove(value)

Example:

Python3

# program to demonstrate use of remove() method

# assign list
numbers = [1, 2, 3, 2, 3, 4, 5]

# use remove()
numbers.remove(3)

# display list
print(numbers)

# use remove()
numbers.remove(2)
Menu
# display list
print(numbers)
Articles Read 
0 of 6 Complete. (0%)


# use remove()
https://practice.geeksforgeeks.org/batch/Datasci-4/track/da-python-data-structure/article/Njc2Mg%3D%3D 10/15
3/24/23, 8:37 PM Practice | GeeksforGeeks | A computer science portal for geeks

numbers.remove(5) Dash

# display list
Articles
print(numbers)

Videos
Output

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

Quiz

pop() method
The pop() method like the del keyword deletes value at a particular index. But the
pop() method returns deleted value from the list.
Syntax:

list_name.pop(index)

Python3

# program to demonstrate use of pop() method

# assign list
numbers = [1, 2, 3, 2, 3, 4, 5]

# use remove()
numbers.pop(3)

# display list
print(numbers)

# use remove()
numbers.pop(-1)
Menu
# display list
print(numbers)
Articles Read 
0 of 6 Complete.
# use (0%)
remove()


https://practice.geeksforgeeks.org/batch/Datasci-4/track/da-python-data-structure/article/Njc2Mg%3D%3D 11/15
3/24/23, 8:37 PM Practice | GeeksforGeeks | A computer science portal for geeks

numbers.pop(0) Dash

# display list
Articles
print(numbers)

Videos
Output

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

Quiz

max() method
This function is used to compute the maximum of the values passed in its argument
and the lexicographically largest value if strings are passed as arguments.

Syntax:

max(a,b,c,..,key,default)
Parameters :
a,b,c,.. : similar type of data.
key : key function where the iterables are passed and comparison is perf
ormed
default : default value is passed if the given iterable is empty
Return Value :
Returns the maximum of all the arguments.
Exceptions :
Returns TypeError when conflicting types are compared.

Example:

Python3

# Python code to demonstrate the working of


# max()
Menu
# printing the maximum of 4,12,43.3,19,100
print("Maximum of 4,12,43.3,19 and 100 is : ",end="")
Articles Read print (max( 4,12,43.3,19,100 ) ) 
0 of 6 Complete. (0%)


https://practice.geeksforgeeks.org/batch/Datasci-4/track/da-python-data-structure/article/Njc2Mg%3D%3D 12/15
3/24/23, 8:37 PM Practice | GeeksforGeeks | A computer science portal for geeks
Dash

Output

Maximum of 4,12,43.3,19 and 100 is Articles


: 100

Videos

min() method
This function is used to compute the minimum
Problems of the values passed in its argument
and lexicographically smallest value if strings are passed as arguments.

Quiz
Syntax:

min(a,b,c,.., key,default)
Parameters :
a,b,c,.. : similar type of data.
key : key function where the iterables are passed and comparison is perf
ormed
default : default value is passed if the given iterable is empty
Return Value :
Returns the minimum of all the arguments.
Exceptions :
Returns TypeError when conflicting types are compared.

Example:

Python3

# Python code to demonstrate the working of


# min()

# printing the minimum of 4,12,43.3,19,100


print("Minimum of 4,12,43.3,19 and 100 is : ",end="")
print (min( 4,12,43.3,19,100 ) )

Output
Menu
Minimum of 4,12,43.3,19 and 100 is : 4

Articles Read 
0 of 6 Complete. (0%)


https://practice.geeksforgeeks.org/batch/Datasci-4/track/da-python-data-structure/article/Njc2Mg%3D%3D 13/15
3/24/23, 8:37 PM Practice | GeeksforGeeks | A computer science portal for geeks
Dash
sort() function
Python list sort() function can be used to sort a List in ascending, descending, or
user-defined order. Articles

Syntax of sort() function


Videos
Syntax: List_name.sort(reverse=True/False, key=myFunc)
Parameter: Problems

reverse: (Optional), reverse=True will sort the list descending.


Default is reverse=False Quiz
key Optional. A function to specify the sorting criteria(s)

Example 1: Sort the List of numbers in Ascending Order


The sort() method by default sort element in ascending order as we can see below
example:

Python3

# Python program to demonestrate to


# sorting numbers in Ascending Order

numbers = [1, 3, 4, 2]
# Sorting list of Integers in ascending
numbers.sort()
print(numbers)

Output

[1, 2, 3, 4]

Menu reverse() method


Python List reverse() is an inbuilt method in the Python programming language
that reverses objects of the List in place i.e.
Articles Read  it doesn’t use any extra space but it just
0 of 6 modifies
Complete. the
(0%)original list. 

https://practice.geeksforgeeks.org/batch/Datasci-4/track/da-python-data-structure/article/Njc2Mg%3D%3D 14/15
3/24/23, 8:37 PM Practice | GeeksforGeeks | A computer science portal for geeks
Dash
Syntax: list_name.reverse()
Parameters: There are no parameters.
Articles

Returns: The reverse() method does not return any value but reverses
the given object from the list.
Videos

Here we are reversing the list using the list reverse() function in Python.
Problems
Python3

Quiz
# Python3 program to demonstrate the
# use of reverse method

# a list of numbers
list1 = [1, 2, 3, 4, 1, 2, 6]
list1.reverse()
print(list1)

# a list of characters
list2 = ['a', 'b', 'c', 'd', 'a', 'a']
list2.reverse()
print(list2)

Output

[6, 2, 1, 4, 3, 2, 1]
['a', 'a', 'd', 'c', 'b', 'a']

Mark as Read

 Report An Issue

If you are facing any issue on this page. Please let us know.
Menu

Articles Read 
0 of 6 Complete. (0%)


https://practice.geeksforgeeks.org/batch/Datasci-4/track/da-python-data-structure/article/Njc2Mg%3D%3D 15/15

You might also like