0% found this document useful (0 votes)
0 views

Lists in Python

Uploaded by

Arnav Rajesh
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
0 views

Lists in Python

Uploaded by

Arnav Rajesh
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 11

Lists in Python

Lists

• A list is a collection of comma separated values or an ordered sequence


of values/items enclosed in square brackets [].
• The items/elements in a list can be of any type such as string, integers,
float, objects or even a list (lists are heterogeneous).
• Lists are mutable, i.e., values in the list can be modified.

Eg:

L1=[10,20,30]

L2=[10, ‘abc’, 39.5,’p’]

L3= [‘apple’, ‘orange’,’banana’]

Note:

Lists are mutable, i.e., values in the list can be modified, which means that
Python will not create a new list when we make changes to an element of a
list.

Eg: In the case of integers,

x=5

y=x, here y and x will be pointing to same value 5.

x 5
y

x=6, now x will be pointing to 6 and y will be pointing to 5

print(x) 6 x 6
print(y) 5 y
5
But in the case of lists,

L1= [10,20,30]

L2=L1

1001

L1 10 20 30

L2

print(id(L1), id(L2) displays the same value( memory address)

L1[1]=40

1001

L1 10 40 30

L2

Declaring/Creating Lists

Syntax

<list_name> = []

Eg: L = [] This construct is termed as “List Display Construct”.

list() method

list() method is used to create a list from an existing sequence types and
convert a given record /tuple or string into list. list() can be used in following
ways,

a) Creating a list from an existing sequence

syntax

<new_list_name> = list(sequence/string)
Example

tup=(10,20,30)

li=list(tup)

print( li) [10, 20, 30]

str="computer"

l2=list(str)

print( l2) ['c', 'o', 'm', 'p', 'u', 't', 'e', 'r']

b) Creating an empty list using list()

Eg: L1= list()

c) Creating a list through user input using list()

Eg: L1= list(input(“Enter the list elements:”)) I/P - python

print(L1) ['p', 'y', 't', 'h', 'o', 'n']

Accessing list elements

An item in a list can be accessed using its index value. Same as strings, list also
have negative and positive index.

Eg: L=list(“python”)

L[1] y

L[6] displays Index Error if we try to access an element that doesn’t


exist in list.

Traversing a List

Accessing each element of a list.

a) Using ‘in’ operator inside for loop

L=list(“python”)

for i in L:

print(i)

Here, in operator using for loop iterates each element of a list in sequence.
b) Using range() function

range() function can be used for accessing individual elements of a list, using
indexes of elements only, along with len() method.

L=list(“python”)

n = len(L)

for i in range(n):

print(L[i])

Comparing Lists

Python allows comparing two lists. It performs element-by-element


comparison. Two lists can be compared using all relational operators if they are
of comparable types, otherwise Python flashes an error.

Integer list and string lists are dissimilar but integer list and float list are equal
if they have matching values.

Operations on Lists

1) Concatenation

Python allows combining or adding of two lists using ‘+’ operator

L1=[1,2,3]

L2=[5,6,7]

L3 = L1 + L2 [1,2,3,5,6,7]

2) Repitition/Replication

* (asterisk) operator replicates the List for a specified number of times and
creates a new list.

L1=[1,2,3]

L1 * 3 [1,2,3,1,2,3,1,2,3]
3) Membership operator

Membership operator is used to check whether a particular element/item is a


member of that sequence or not.

a) in operator - checks whether a given item is contained in a list. If the


item appears it returns True

b) not in operator – Returns True if the item does not appear in the list.

4) List Slicing

Indexing and slicing are two inter-related operations in lists. Slicing is done
through indexing. Slicing is an operation in which we can slice a particular
range from that sequence. While indexing is used to obtain individual items,
slicing allows us to obtain a subset of items.

5) Copying List

L1=[1,2,3]

L2=L1 This statement does not create a new list, it makes L2 and L1 refer to
the same list object. L2 is an alias of L1. Any changes made to either of them
will be reflected in the other list.

Methods to create a copy of the list

a) L2=L1 using assignment operator

b) L2=L1[:] Slice original list and store it into a new list

c) L2= list(L1) Using list()

d) Using copy()

import copy

L2=copy.copy(L1)
BUILT – IN FUNCTIONS

1. len()
This function returns the length of the list.
syntax
len(listname)
2. Updating a list
We can assign new value to the existing list using assignment operator.
List[index]=new value
3. append()
It adds a single item to the end of the list. It doesn’t create a new list;
rather it modifies the original list. The single element can also be a list.
Syntax
List.append(item)
Eg:
L1= [4, 5, 6]
L1.append(7) O/P L1=[4,5, 6,7]
L1.append([10,20]) O/P L1=[4, 5, 6, 7,[10,20]]
4. extend()
This method adds one list at the end of another list. All the items of a list
are added at the end of an already created list.
Syntax
List1.extend(list2)
Eg:
L1= [4, 5, 6]
L2=[10,20]
L1.extend(L2) O/P L1=[4, 5, 6, 10, 20]
5. insert()
This method is used to insert an element at a specified index. This
function takes two arguments: the index where an item to be inserted
and the item itself.
Syntax
List_name.insert(index_number, value)
Eg:
L1= [4, 5, 6]
L1.insert(1, 10) O/P - L1= [4, 10, 5, 6]
6. reverse()
This function reverses the items of the list. It doesn’t create a new list.
Syntax
List.reverse()
Eg:
L1= [4, 5, 6]
L1.reverse() O/P- L1= [6, 5, 4]

7. index()
This function returns the index of the first occurrence of an item from
the list. If the item isn’t present, Value Error is generated.
Syntax
List.index(item)
8. sort()
This function sorts the items of the list, by default in ascending order. It
doesn’t create a new list.
Syntax
List.sort()
For string elements in a list, sorting is done on the basis of their ASCII
values.
To sort the elements in decreasing order write the statement as
List.sort(reverse=True)
9. clear()
This method removes all items from the list.
Syntax
List.clear()
10.count()
This method counts how many times an element has occurred in a list
and returns it.
Syntax
List.count(element)
Deletion Operators

The operators used to remove or delete an item from the list.

1) pop()

• It removes the element from the specified index and also returns the
removed element.
• If no index value is specified in pop(), then the last element is
deleted.
• pop() can be used with negative index value also.
• If an out of range index is provided, the code will result in runtime
error.
Syntax
List.pop(index)
Eg: L= [3, 4, 5, 6, 7]
L.pop(2) O/P - 5
print(L) O/P - [3, 5, 6, 7]
L.pop() O/P - 7

2) del statement

• del statement removes the specified element from the list but
doesn’t returns the deleted value.
• If an out of range index is provided, the code will result in runtime
error.
• del can be used with negative index value also.
• del can be used with slicing also.

Eg: L= [3, 4, 5, 6, 7]

del L[2]

print(L) O/P - [3, 4, 6, 7]

3) remove()

remove() is used when we know the element to be deleted, not the index of
the element.

Syntax
List.remove(element)
Eg: L= [3, 4, 5, 6, 7]
L.remove(5)

print(L) O/P - [3, 4, 6, 7]

Output Questions

1) L = [10,20,30,40,50]

L[2:5]

L[1:]

L[:4]

L[::]

L[2:5] + L[-4:]

print(L[5])

L[2:5] + L[1]

2) L1= [10, 20, 30, 40]

L2 = [60, 70, 80]

L3, L4=[‘60’,’70’,’80’], [60.0,70.0,80.0]

L5=[60.0,70.1,80.0]

L6=[60,[70,80]]

L = L1 + L2

print(L)

print(L1 + [4])

print(L1 + 4)

print(L2==L3)

print(L2==L4)

print(L2==L6)
print(L2<L4)

print(L2==L5)

print(10 in L1)

print([70] in L6)

print([70,80] in L6)

3) L= [30, 40, 56.7, ‘python’, 45.6, [9,8,7],‘string’]

print(L[1:4])

print(L[-3:])

print(L[2:-2])

print(L[5])

print(L[5][1])

print(L[3]+L[-1])

print(L[3][2])

Programs

1. Create a list of student names and display the names.

2. Enter the elements in a list using user input

You might also like