0% found this document useful (0 votes)
11 views17 pages

15 Lecture Lists

This document provides information about lists in Python. It defines lists as a sequence of values that can be of any data type. Lists are created using square brackets and their elements can be accessed using indexes. Lists are mutable, meaning their elements can be modified. Various list methods and operations like append, pop, sort, and slicing are also described.

Uploaded by

wh14257
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)
11 views17 pages

15 Lecture Lists

This document provides information about lists in Python. It defines lists as a sequence of values that can be of any data type. Lists are created using square brackets and their elements can be accessed using indexes. Lists are mutable, meaning their elements can be modified. Various list methods and operations like append, pop, sort, and slicing are also described.

Uploaded by

wh14257
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/ 17

PYTHON Programming (CST310)

Lecture 15: Lists in Python

Department of Computer Science and Engineering


National Institute of Technology, Srinagar, Jammu and Kashmir
September 12, 2023
Lists
• The list is one of the most widely used data types in Python.
• Like a string, a list is a sequence of values.
• In a string, the values are characters, but in a list, they can be any type.
• The values in list are called elements or sometimes items.
• Lists are used to store the data items where each data item is separated by a
comma (,).
• A Python List can have data items of any data type, be it an integer type or a
boolean type.
• There are several ways to create a new list.
• The simplest is to enclose the elements in square brackets (“[" and “]”)
For example: [1, 20, 30, 40] #this is list of 4 integers.
[“Prince”, “Abhishek”, “Akshita”, “Prudhvi”] # list of 4 strings
Creating Lists
a= [1, 20, 30, 40] #this is list of 4 integers assigned to variable ‘a’.
b= [“Shubham”, “Lokit”, “Sankalp”, “KP”] # list of 4 strings assigned to ‘b’

c= [ 2.5, “Nit”, 24] #The elements of a list don’t have to be the same type

d= [ “Srinagar”, “Jammu”, [“JU”, “KU”, 23]] # This is nested list, i.e., list in
another list.
• A list with no elements is called as an empty list. An empty list can be
created as:
empty= []
Accessing List values or Elements
• Like Strings, the elements of Lists can be accessed using the indexes.
List_name[index]
• Indexing in a List are of two types:
1. Positive Indexing – Here the indexing starts from 0, moving from left
to right.
2. Negative Indexing – In this, the indexing starts from right to left and
the rightmost element has an index value of -1.
a = ['Hello', 1, 4.63, True, "World", 2.0, "False"]
Lists are Mutable
• Unlike Strings which are immutable, Lists are mutable which means
that the value of elements of Lists can be modified.
• you can change the order of items in a list or reassign an item in a list.
• Delete an element, add new element, update the value of an element
of a list.
For example:
a= [ 2020, “NIT Srinagar”]
a[0]=2020
print(a) #[2020,”NIT SRINAGAR”]
In operator Works in Lists
CSE2021= [ “Vikram”, “Arjun”, “Danish”]
>>> “Danish” in CSE2021
True

>>> “Aman” in CSE2021


False
Traversing the elements of a List
• The most common way to traverse the elements of a list is with a for loop.
• The syntax is the same as for strings:
for item in list_name:
print(item)
The above syntax is used when we just want to read the elements of list
• Using Index values also, the elements can be traversed as follow:
for i in range(len(list_name)):
list_name[i]=list_name[i]*3
print(list_name)
This method of traversal is used when we also want to update the elements of
list
What will be the Output?
x=[]

for item in x:
print(“hello”)
Traversing a Nested List
• A nested List contains another list as its element.
• For example: a= [“Car”, “Bike”, [“Bicycle”, “ Rikshaw”]]

for item in a:
print(item)

Although a list contain another list, the nested list still counts as a
single element.
Traversing a Nested List
How to Traverse all the elements of a List (including the nested list
element)?

a= ["Car", "Bike", ["Bicycle", "Rikshaw"]]

Output:
How to Traverse all the elements of a List
(including the nested list element)?
a= ["Car", "Bike", ["Bicycle", "Rikshaw"]]

for item in a:
if str(type(item)).find('list')!=-1:
for i in item:
print(i)
else:
print(item)
List operations
1. + Operator: between two lists performs the concatenation of two lists.
a= [ 1, 2, 3]
b= [10, 20, 30]
C=a+b #will return [1, 2, 3, 10, 20, 30]

2. The * operator repeats a list a given number of times.


a=['shivam', 'aman']
print(a*3)
['shivam', 'aman', 'shivam', 'aman', 'shivam', 'aman']
List Slicing
• The slice operator also works on lists.
t = ['a', 'b', 'c', 'd', 'e', ‘f’]
t[1:3] #will return a list [‘b’, ‘c’]
t[:] #will return a list containing all the elements of a list t
t[2:] # will return list containing elements from index 2 till end.

Since lists are mutable, it is often useful to make a copy before


performing operations.
t[1:3] = ['x', 'y’]
print(t) #outputs['a', 'x', 'y', 'd', 'e', 'f']
List Methods
Python provides methods that operate on lists.
1. Append: this method is used to add new element to a list in the end of
the list.
For example: a=[ 62, 30, 50]
a.append(300) #will append 300 in the list a in last.
2. Extend: this method takes a list as argument and append all the
elements of that list to the main list.
b= [300, 500]
a.extend(b)
Print(a) # outputs [62, 30, 50, 300, 500]
3. Sort: this method arranges the elements of the list from low to high.
a.sort() # will sort the list a in ascending order
Most list methods are void; they modify the list and return None.
a=a.sort() # Output? None
List Methods
4. Clear: this method will delete all the elements of a list and return
empty list.
For example: a.clear()
5. Count: this method counts the occurrence of a element in a list.
a.count(23)
6. Reverse: this method reverses the list.
7. insert(): this method inserts new element in a specified index.
a.insert(2,’cse’)
Deleting element from a list
• There are several ways to delete elements from a list.
• If you know the index of the element you want, you can use pop:
t = ['a', 'b', 'c’]
t.pop(1) # will pop the element at index 1

Pop method modifies the list and returns the element that was
removed.
x= t.pop(1)
If you don’t provide an index, it deletes and returns the last element.
Deleting elements of a List
• If you know the element you want to remove (but not the index), you
can use remove:
t.remove(10) # this will remove the first occurrence of
element 10 from the list.
if element to delete is not in list, then this method gives
“ValueError: element not in list” exception
To delete more than one values, use the del method with slice operator
del t[2:3]

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy