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

7. Lists in python

The document provides a comprehensive overview of lists in Python, detailing their structure, creation, and manipulation methods. It covers list indexing, slicing, membership operators, and various built-in functions and methods for list operations. Additionally, it explains concepts like nested lists and list comprehensions for efficient data handling.

Uploaded by

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

7. Lists in python

The document provides a comprehensive overview of lists in Python, detailing their structure, creation, and manipulation methods. It covers list indexing, slicing, membership operators, and various built-in functions and methods for list operations. Additionally, it explains concepts like nested lists and list comprehensions for efficient data handling.

Uploaded by

Soham Mukherjee
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 19

Lists in Python

A list is a data-structure, that can store multiple data. A list is dynamic and mutable type,
i.e., we can add and delete elements from the list. The values that make up a list are called
its elements. Each list value is a single element in the list. The elements are indexed
according to a sequence and the indexing is done with 0 as the first index.

To create a list, you separate the elements with a comma and enclose them with a bracket
“[]”.

Syntax:
<name of list> = [ <value1>, <value2>, <value3> ]

For example:
1. list1 = [67, 82, 98, 92, 78, 87] - numeric list
2. list2 = ['Pen', 'Pencil', 'Rubber'] - a character/string list
3. list3 = ['A V Raman', 35,'TGT Computer'] - a list with multiple type values
4. list4 = [] - an empty list

1
We can access individual list elements using its index value and a range of elements using
slicing. A list index starts from 0.

Python indexes the list element from left to right and from right to left. From left to right,
the first element of a list has the index 0 and from right end to left, the extreme right index
element of a list is –1. Individual elements in a list can be accessed by specifying the list
name followed by a number in square brackets ( [ ]).
L1= [67, 82, 98, 92, 78, 87]

List 67 82 98 92 78 87
Left to Right 0 1 2 3 4 5
Right to Left -6 -5 -4 -3 -2 -1

2
Lists are mutable, which means we can change their elements.
Using the bracket operator ([ ]) on the left side of an assignment, we can update one of
the elements.
For example:

# a list with 5 numbers


# 0th position value changed with new value 6
# last position value changed with new value 7

Same memory address

3
Traversing a List
#1:Using for loop #2:For loop and range()
list1 = [1, 3, 5, 7, 9] list1 = [1, 3, 5, 7, 9]
for i in list1: length = len(list1)
print(i) for i in range(length):
print(list1[i])

#3: Using while loop #4:List Comprehension


list = [1, 3, 5, 7, 9] list = [1, 3, 5, 7, 9]
length = len(list) [print(i) for i in list]
i=0
while i < length:
print(list[i])
i += 1

4
Slicing List Elements
Selecting a slice is similar to selecting an element(s) of a list. Subsets of lists can be taken
using the slice operator with two indices in square brackets separated by a colon.

<List name> [start:stop:step]

start: Starting index where the slicing of object starts.


stop: Ending index where the slicing of object stops. (index-1)
step: It is an optional argument that determines the increment between each index
for slicing.

For example:
list1 = [67, 82, 98, 92, 78, 87]
print (list1[2:5]) [98, 92, 78]
print (list1[5:1:-2]) [87, 92]
print(list1[1:4:2]) [82, 92]

5
Operators in Lists
Membership Operators:
in - This operator tests if an element is present in list or not. If an element exists in the list,
it returns True, otherwise False.
a = [1, 5, 12,10]
print(1 in a)
o/p: True

not in - The not in operator evaluates True if it does not find a variable in the specified
sequence, otherwise False.
a = [1, 5, 12,100]
print(1 not in a)
o/p: False

Concatenation Operator(+) – This operator concatenates two lists with each other and
produces a third list.
a = [2, 3,4]
b = [1, 5, 6]
c=a+b
print (c)
o/p: [2, 3, 4,1, 5, 6]

Replicating Operator(*) -This operator repeatedly concatenates the lists.

a = [2, 3,4]
print (a * 2)
o/p: [2, 3, 4,2, 3, 4]

7
List Functions and Methods
Python has a complete list of public methods that may be called on any list object. The dot
operator (.) is used along with the list to access list functions len() function.

1. len() - This method returns the length of the list.

Syntax:
len(<List>)

Num = [23, 54, 34,69, 54]


print (len(Num)) # o/p: 5

2. append() - This method appends an element at the end of an existing list.

Syntax:
<List>.append(55)

Num = [23, 54, 34,69, 54]


Num.append(55) # append 55 at the end of the list
print (Num) # o/p: [23, 54, 34,69, 54, 55] 8
3. insert() - This method inserts an element/object into a list at the index position.

Syntax:
<List>.insert(index,value)

Num = [23, 54, 34,69, 54]


Num.insert(3, 77) # insert 77 at 4th place
print (Num) # prints: [23, 54, 34, 77,69, 54]

4. pop() - This method removes and returns last object or element from the list.

Syntax:
<List>.pop()

Num = [1,2,3,4,5]
Num.pop() # removes the last element from the list

Num.pop(2) # removes the 3rdelement, i.e., 3


print(Num) # o/p: [1,2,4]
9
5. remove() - This method removes the element which is passed as an argument.

Syntax:
<List>.remove(element)

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


Num.remove(3) Num.remove(1)
print(Num) # o/p: [1,2,4,5] print(Num) # o/p: [2, 1, 4]

6. extend() - This method appends a list into another list. This method does not return any
value but adds the content to the existing list.

Syntax:
<List1>.extend(<list2>)

N1 = [1,2,3,4]
N2 = [5,6,7,8]
N1.extend(N2) # o/p: [1,2,3,4,5,6,7,8]
print (N1)
10
7. count() - This method returns count of how many times a given element occurs in list.
Syntax:
<List>.count(element)
list1 = [1, 1, 2, 3, 2, 1]
s=list1.count(1)
print(s) # o/p: 3

8. index() - This method searches for given element from start of the list and returns the
lowest index where the element appears.

Syntax:
<list>.index(element, start, end)

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


a=list1.index(4) print(list1.index(4, 4, 8))
print(a) # o/p: 2 print(list1.index(1, 1, 7)) # o/p: 6
4
11
9. reverse() - This method reverses the given elements from the list. It does not return any value.

Syntax:
<list>.reverse()

list1 = [1, 2, 2, 6]
list1.reverse()
print(list1) # o/p: [6, 2, 2, 1]

10. sort() - This method is used to sort a list in ascending, descending or user defined order.
To sort the list in ascending order. It does not return any value.

Syntax:
<list>.sort(reverse=False/True

12
By default, reverse takes False value
11. max() - This function returns the item with the highest value in the list. If the values
are strings, an alphabetically comparison is done.
Syntax
max(<list>)

12. min() - This function returns the item with the highest value in the list. If the values
are strings, an alphabetically comparison is done.
Syntax
min(<list>)

13
13. sum() – This function is used to display sum of the numbers in the list.

Syntax
sum(iterable,start)

iterable : iterable can be a list , tuple or dictionary , but most importantly it should be
numbers.

start : It is added to the sum of numbers in the iterable. If start is not given in the syntax , it
is assumed to be 0.

14
list() - This function returns a sequence list of elements. The iterable argument is optional.
You can provide any sequence or collection (such as a string, list, tuple, set, dictionary, etc).
If no argument is supplied, an empty list is returned.

Syntax
list([iterable])

Deleting List Elements using del Statement


The del statement and the pop()method is used to delete elements from a list. But the
difference is that del statement deletes the element but does not return the removed
item, except that pop() method returns the deleted element.

For example:
>>> Num = [23, 54, 34, 44, 35]
>>> del Num[4] # deletes the 5th element, i.e., 35
>>> print (Num) # o/p: [23, 54, 34, 44] 15
Linear Search:

The program takes a list and key as # Program on Linear Search


input and finds the index of the key in
the list using linear search. items = [10,45,34,5,7,10]
x = int(input("enter item to search:"))
• This is the simplest searching i = flag = 0
technique. while i < len(items):
if items[i] == x:
• It sequentially checks each element flag = 1
of the list for the target searching value break
until a match is found or until all the i=i+1
elements have been searched. if flag == 1:
print("item found at position:", i + 1)
• This searching technique can be else:
performed on both type of list, either print("item not found")
the list is sorted or unsorted.

16
Nested Lists:

• A nested list is a list that appears as an element in another list.


• In the list1, the element with index 3 is a nested list. If we print(list1[3]), we get [10, 20].
To extract an element from the nested list, we can proceed in two steps. First, extract
the nested list, then extract the item of interest.
list1= ["hello", 2.0, 5, [10, 20]]
innerlist = list1[3]
print(innerlist)
item = innerlist[1]
print(item)

• It is also possible to combine those steps using bracket operators that evaluate from left
to right.
print(list1[3][1])

17
Comprehension
Comprehensions in Python provide us with a short and concise way to construct new
sequences (such as lists, set, dictionary etc.) using sequences which have been already
defined.
Syntax:
SEQUENCENAME=[expression for item in list]
Example:

list_using_comp = [var**2 for var in range(1,10)]

#Output
[1, 4, 9, 16, 25, 36, 49, 64, 81]

List comprehensions can utilize conditional statement to modify existing list (or
other tuples). We will create list that uses mathematical operators, integers, and
range().
18
Example : Using if with List Comprehension

number_list = [ x for x in range(20) if x % 2 == 0] print(number_list)

output will be: [0, 2, 4, 6, 8, 10, 12, 14, 16, 18]

Example : Nested IF with List Comprehension

num_list = [y for y in range(100) if y % 2 == 0 if y % 5 ==0] print(num_list)

Output will be: [0, 10, 20, 30, 40, 50, 60, 70, 80, 90]
Here, list comprehension checks:
Is y divisible by 2 or not?
Is y divisible by 5 or not?
If y satisfies both conditions, y is appended to num_list.
19

You might also like