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

Class 14 List Methods 2

The document discusses various list methods in Python. It summarizes: 1. List methods like index(), count(), pop(), remove(), reverse(), sort(), insert(), and copy() are described along with examples of their usage and outputs. 2. The index() method returns the index of the first occurrence of an element. The count() method returns the number of occurrences. 3. The pop() method removes and returns an element at a given index, or the last element by default. 4. Methods like reverse(), sort(), and insert() modify the list in-place by reversing, sorting, or inserting elements respectively.

Uploaded by

TheAncient01
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)
64 views17 pages

Class 14 List Methods 2

The document discusses various list methods in Python. It summarizes: 1. List methods like index(), count(), pop(), remove(), reverse(), sort(), insert(), and copy() are described along with examples of their usage and outputs. 2. The index() method returns the index of the first occurrence of an element. The count() method returns the number of occurrences. 3. The pop() method removes and returns an element at a given index, or the last element by default. 4. Methods like reverse(), sort(), and insert() modify the list in-place by reversing, sorting, or inserting elements respectively.

Uploaded by

TheAncient01
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

Class_14_List_Methods_2

May 13, 2023

[1]: # append(), extend()

1 index()
• It returns the index of the first occurence from left to right.
• If the element is not found then it returns value error.

[7]: # lst.index(element)
# lst.index(element,start_index)
# lst.index(element,start_index,stop_index)
# stop_index is excluded

[5]: lst=[True, 'Python', 10, True, 50, 5+5j, 2.5,'Python']

print(lst.index('Python'))
print(lst.index(True))

1
0

[6]: print(lst.index(100))

---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
~\AppData\Local\Temp\ipykernel_17228\2018578910.py in <module>
----> 1 print(lst.index(100))

ValueError: 100 is not in list

[8]: lst.index('Python',2)

[8]: 7

[9]: lst.index('Python',2,6)

---------------------------------------------------------------------------
ValueError Traceback (most recent call last)

1
~\AppData\Local\Temp\ipykernel_17228\1525388542.py in <module>
----> 1 lst.index('Python',2,6)

ValueError: 'Python' is not in list

2 count()
• It returns the number of occurences of an element.

[12]: lst=[10,20,30,10,20,30,50,60,70,80,10,20,50,90]

print(lst.count(10))
print(lst.count(20))
print(lst.count(100))

3
3
0

3 pop()
• It returns the element availanle at a particular index and removes that element from the list.
• By default it returns and removes the last element.
• For invalid index it returns index error.

[15]: # lst.pop(index)

[18]: lst=[True, 'Hello', 'Python', False, 5+5j, {1:100,2:200}, (1,2,3)]


print(lst)

[True, 'Hello', 'Python', False, (5+5j), {1: 100, 2: 200}, (1, 2, 3)]

[19]: x=lst.pop(2)
print(x)

Python

[20]: print(lst)

[True, 'Hello', False, (5+5j), {1: 100, 2: 200}, (1, 2, 3)]

[21]: x=lst.pop()
print(x)

(1, 2, 3)

[22]: print(lst)

[True, 'Hello', False, (5+5j), {1: 100, 2: 200}]

2
[24]: lst.pop(50)

---------------------------------------------------------------------------
IndexError Traceback (most recent call last)
~\AppData\Local\Temp\ipykernel_17228\655153165.py in <module>
----> 1 lst.pop(50)

IndexError: pop index out of range

[25]: lst=[True, 'Hello', 'Python', False, 5+5j, {1:100,2:200}, 'Hello', (1,2,3)]


print(lst)

[True, 'Hello', 'Python', False, (5+5j), {1: 100, 2: 200}, 'Hello', (1, 2, 3)]

[26]: lst.pop(6)

[26]: 'Hello'

[27]: lst

[27]: [True, 'Hello', 'Python', False, (5+5j), {1: 100, 2: 200}, (1, 2, 3)]

[28]: print(lst.pop())
print(lst)

(1, 2, 3)
[True, 'Hello', 'Python', False, (5+5j), {1: 100, 2: 200}]

[29]: print(lst.pop())
print(lst)

{1: 100, 2: 200}


[True, 'Hello', 'Python', False, (5+5j)]

[30]: print(lst.pop())
print(lst)

(5+5j)
[True, 'Hello', 'Python', False]

[31]: print(lst.pop())
print(lst)

False
[True, 'Hello', 'Python']

[32]: print(lst.pop())
print(lst)

3
Python
[True, 'Hello']

[33]: print(lst.pop())
print(lst)

Hello
[True]

[34]: print(lst.pop())
print(lst)

True
[]

[35]: print(lst.pop())
print(lst)

---------------------------------------------------------------------------
IndexError Traceback (most recent call last)
~\AppData\Local\Temp\ipykernel_17228\3044658256.py in <module>
----> 1 print(lst.pop())
2 print(lst)

IndexError: pop from empty list

4 remove()
• It removes the first occurence of the specified element from left to right.
• If element is not available then it throws value error.

[36]: # lst.remove(element)

[38]: lst=[True, 'Hello', 'Python', False, 5+5j, True, {1:100,2:200}, 'Hello',␣


↪(1,2,3)]

print(lst)

[True, 'Hello', 'Python', False, (5+5j), True, {1: 100, 2: 200}, 'Hello', (1, 2,
3)]

[39]: lst.remove(True)

[40]: lst

[40]: ['Hello', 'Python', False, (5+5j), True, {1: 100, 2: 200}, 'Hello', (1, 2, 3)]

[41]: lst.remove('Hello')

4
[42]: lst

[42]: ['Python', False, (5+5j), True, {1: 100, 2: 200}, 'Hello', (1, 2, 3)]

[43]: lst.remove(True)

[44]: lst

[44]: ['Python', False, (5+5j), {1: 100, 2: 200}, 'Hello', (1, 2, 3)]

[45]: lst.remove(True)

---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
~\AppData\Local\Temp\ipykernel_17228\749527309.py in <module>
----> 1 lst.remove(True)

ValueError: list.remove(x): x not in list

5 reverse()
• It reverses the list.
• It makes the changes in the existing list.

[46]: lst

[46]: ['Python', False, (5+5j), {1: 100, 2: 200}, 'Hello', (1, 2, 3)]

[47]: lst.reverse()

[48]: lst

[48]: [(1, 2, 3), 'Hello', {1: 100, 2: 200}, (5+5j), False, 'Python']

6 sort()
• It sorts the list in ascending order.

[49]: lst=[20,10,50,0,9,45,7,23,1,65,42,79,32]
print(lst)

[20, 10, 50, 0, 9, 45, 7, 23, 1, 65, 42, 79, 32]

[50]: lst.sort()

[51]: lst

5
[51]: [0, 1, 7, 9, 10, 20, 23, 32, 42, 45, 50, 65, 79]

7 Descending order
[52]: lst=[20,10,50,0,9,45,7,23,1,65,42,79,32]
print(lst)

[20, 10, 50, 0, 9, 45, 7, 23, 1, 65, 42, 79, 32]

[53]: lst.sort(reverse=True)

[54]: lst

[54]: [79, 65, 50, 45, 42, 32, 23, 20, 10, 9, 7, 1, 0]

[56]: lst=[20.68,10,5.9,0,9,45,7,23.5,1,65,42,79,32]
print(lst)

[20.68, 10, 5.9, 0, 9, 45, 7, 23.5, 1, 65, 42, 79, 32]

[57]: lst.sort()

[58]: lst

[58]: [0, 1, 5.9, 7, 9, 10, 20.68, 23.5, 32, 42, 45, 65, 79]

[59]: lst=[20.68,10,5.9,0,9,45,7,23.5,1,'A','Z','Q','K']
print(lst)

[20.68, 10, 5.9, 0, 9, 45, 7, 23.5, 1, 'A', 'Z', 'Q', 'K']

[60]: lst.sort()

---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
~\AppData\Local\Temp\ipykernel_17228\4027238925.py in <module>
----> 1 lst.sort()

TypeError: '<' not supported between instances of 'str' and 'int'

[61]: lst=['A','Z','Q','K']
print(lst)

['A', 'Z', 'Q', 'K']

[62]: lst.sort()

[63]: lst

6
[63]: ['A', 'K', 'Q', 'Z']

[64]: 5<'A'

---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
~\AppData\Local\Temp\ipykernel_17228\502391825.py in <module>
----> 1 5<'A'

TypeError: '<' not supported between instances of 'int' and 'str'

[65]: 5<ord('A')

[65]: True

[66]: 'A'<'X'

[66]: True

[68]: # print(dir(lst))

8 insert()
• It is used to insert an element at a particular index.
• The preveious element at that particular index is shifted to the right.

[69]: # lst.insert(index,element)

[71]: lst=['Hello',True,'Python',10,2.5,None]
print(lst)

['Hello', True, 'Python', 10, 2.5, None]

[72]: lst.insert(2,'Java')

[73]: lst

[73]: ['Hello', True, 'Java', 'Python', 10, 2.5, None]

[74]: lst.insert(-1,{1:100})

[75]: lst

[75]: ['Hello', True, 'Java', 'Python', 10, 2.5, {1: 100}, None]

7
9 copy()
• It copies the eleemnts from the list and returns a new list with the same elements.

[82]: lst=[10,20,30,40,50]
print(lst)

lst2=lst
print(lst2)

lst2[0]=None
print(lst2)

print(lst)

print(id(lst))
print(id(lst2))

[10, 20, 30, 40, 50]


[10, 20, 30, 40, 50]
[None, 20, 30, 40, 50]
[None, 20, 30, 40, 50]
2168035550528
2168035550528

[93]: lst=[10,20,30,40,50]
print(lst)

lst2=lst.copy()

print(lst2)

lst2[0]=None
print(lst2)

print(lst)

lst[2]=5000
print(lst)

print(lst2)
print(id(lst))
print(id(lst2))

[10, 20, 30, 40, 50]


[10, 20, 30, 40, 50]
[None, 20, 30, 40, 50]
[10, 20, 30, 40, 50]
[10, 20, 5000, 40, 50]

8
[None, 20, 30, 40, 50]
2168036215872
2168035549632

[94]: lst=[10,20,30,40,50]
print(lst)

lst2=lst.copy()

print(lst2)

[10, 20, 30, 40, 50]


[10, 20, 30, 40, 50]

[95]: print(id(lst))
print(id(lst2))

2168036078464
2168035550528

[100]: print(id(lst[0]))
print(id(lst2[0]))

2167922715216
2167922715216

[101]: # - 5 to 256

10 List is mutable

11 Mutability
• We can modify the values after definition.
• Item assignment is possible.
• The addresses remain the same before and after the modification.

[104]: lst=[10,20,30,40,50]
print(lst,id(lst))

lst[0]=1000
print(lst)

print(id(lst))

[10, 20, 30, 40, 50] 2168036181504


[1000, 20, 30, 40, 50]
2168036181504

9
12 String is immutable
[106]: my_str='Python'
print(my_str)

Python

[107]: my_str[0]='A'

---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
~\AppData\Local\Temp\ipykernel_17228\2860150867.py in <module>
----> 1 my_str[0]='A'

TypeError: 'str' object does not support item assignment

[109]: my_str='Python'
print(my_str)
print(id(my_str))

my_str=my_str.replace('P','A')
print(my_str)
print(id(my_str))

Python
2167925102704
Aython
2168047845104

13 Tuple
[118]: # Anything inside the () is a tuple.
# A tuple is a container type that can contain multiple elements.
# A tuple can contain heterogenous (different type) elements too.
# A tuple can contain duplicate elements too.

[116]: t=(1,2,3,4,5,6)
print(t,type(t))

(1, 2, 3, 4, 5, 6) <class 'tuple'>

[117]: t=(True, False, 0, None, 'Hello', 2.5, {1:100,2:200}, [10,20,30])


print(t,type(t))

(True, False, 0, None, 'Hello', 2.5, {1: 100, 2: 200}, [10, 20, 30]) <class
'tuple'>

10
[120]: t=(1,2,3,4,5,2,1,4,5,6,2,1,4,8,5,3,2,1,4,5,2,4)
print(t,type(t))

(1, 2, 3, 4, 5, 2, 1, 4, 5, 6, 2, 1, 4, 8, 5, 3, 2, 1, 4, 5, 2, 4) <class
'tuple'>

14 List vs Tuple
[121]: # List is mutable whereas tuple is immutable

15 Immutability
• We can not modify the values after definition.
• Item assignment is not possible.
• Addresses are different after modification.

[122]: lst=[10,20,30,40,50]
print(lst)

[10, 20, 30, 40, 50]

[123]: lst[0]=5000
print(lst)

[5000, 20, 30, 40, 50]

[124]: t=(10,20,30,40,50)
print(t)

(10, 20, 30, 40, 50)

[125]: t[0]=1000

---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
~\AppData\Local\Temp\ipykernel_17228\475506145.py in <module>
----> 1 t[0]=1000

TypeError: 'tuple' object does not support item assignment

16 Operations on a tuple
[126]: # Length
# Concatenation
# Repetition
# Indexing and slicing

11
17 Length
• The number of elements in a tuple is the length of the tuple.

[127]: # len(t)

[129]: t=(10,20,30,40,50)
print(t)

print(len(t))

(10, 20, 30, 40, 50)


5

18 Concatenation
• Joining or adding two or more tuples together is known as concatenation.

[130]: # + operators is used to concatenate two or more tuples

[136]: t=(10,20,30,40,50)
t2=(True, False, None, [1,2,3])

print(t)
print(t2)
print(id(t))

(10, 20, 30, 40, 50)


(True, False, None, [1, 2, 3])
2168036257360

[137]: t=t+t2
print(t)
print(id(t))

(10, 20, 30, 40, 50, True, False, None, [1, 2, 3])
2168038884512

[138]: # w3schools.com

19 Repetition
[139]: # * operator is used to perform the repetition on a tuple

[140]: t=(10,20,30,40,50)
print(t)

(10, 20, 30, 40, 50)

12
[141]: t*2

[141]: (10, 20, 30, 40, 50, 10, 20, 30, 40, 50)

[142]: t*3

[142]: (10, 20, 30, 40, 50, 10, 20, 30, 40, 50, 10, 20, 30, 40, 50)

[146]: # Create a tuple that has 15 times 10

(10,)*15

[146]: (10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10)

[147]: [10]*15

[147]: [10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10]

20 Indexing
• A tuple is ordered collection of data because each element of a tuple is stored at a particular
index.
• A tuple is also called as sequence type because it follows the indexing method.
• A tuple supports +ive and -ive indexing both.

[149]: t=(10,20,30,40,50,60)
print(lst)

[5000, 20, 30, 40, 50]

21 +ive index
• +ive index are from left to right.
• It starts from 0 by default.
• The index of the last element is len(t)-1

22 -ive index
• It is from right to left
• The start is -1 by default.
• The index of the last element is -len(t)

[163]: t=(10,20,30,40,50,60)
print(t)

# Fetch the first element of the tuple.

13
print(t[0])
print(t[-6])
print(t[-len(t)])

# Fetch the last element of the tuple.

print(t[-1])
print(t[5])
print(t[len(t)-1])

# Fetch 30

print(t[2])
print(t[-4])

(10, 20, 30, 40, 50, 60)


10
10
10
60
60
60
30
30

23 Slicing
[164]: # t[start:stop:step]
# Stop is excluded

[170]: t=(10,20,30,40,50,60)
print(t)

# Fetch the first three elements


print(t[0:3])
print(t[0:3:1])
print(t[:3])
print(t[:3:1])

(10, 20, 30, 40, 50, 60)


(10, 20, 30)
(10, 20, 30)
(10, 20, 30)
(10, 20, 30)

[174]: print(t[:3:2])

(10, 30)

14
[178]: print(t)

(10, 20, 30, 40, 50, 60)

[180]: # Reverse the tuple

print(t[::-1])

print(t[-3::-1])
print(t[-3::-2])

(60, 50, 40, 30, 20, 10)


(40, 30, 20, 10)
(40, 20)

[181]: print(t)

(10, 20, 30, 40, 50, 60)

[182]: t[-2:-len(t)+2:-2] # [-2:-4:-2]

[182]: (50,)

[192]: t[-2:-len(t)-2:-2] #[-2:-8:-2]

[192]: (50, 30, 10)

[187]: -len(t)-2

[187]: -8

[193]: # 50,30,10

[199]: # t[::]

24 How to create a tuple

25 Case_1
• When we already know the elements.

[200]: t=(True, False, 'Hello','Python', (1,2,3), [10,20,30])


print(t,type(t))

(True, False, 'Hello', 'Python', (1, 2, 3), [10, 20, 30]) <class 'tuple'>

[201]: #Take a string from user and check if it is:-


# 1. alphanumeric
# 2. alphabets

15
# 3. digit
# 4. all letters are in lower case
# 5. all letters are in upper case
# 6. in title case
# 7. a space character
# 8. numeric
# 9. all number elements in string are decimal

[206]: a=input('Enter a string- ')


print(a,type(a))

if a.isalnum():
print('Alphanumeric')
else:
print('Not alphanumeric')

Enter a string- @!#@#@$


@!#@#@$ <class 'str'>
Not alphanumeric

[208]: a=input('Enter a string- ')


print(a,type(a))

if a.isalpha():
print('Alphabets')
else:
print('Not alphabets')

Enter a string- bdhsvdh


bdhsvdh <class 'str'>
Alphabets

26 find and index


[212]: a='Hello'
print(a.find('l'))
print(a.index('l'))

2
2

[214]: a='Hello'
print(a.find('x'))
print(a.index('x'))

-1

---------------------------------------------------------------------------
ValueError Traceback (most recent call last)

16
~\AppData\Local\Temp\ipykernel_17228\100989827.py in <module>
1 a='Hello'
2 print(a.find('x'))
----> 3 print(a.index('x'))

ValueError: substring not found

[224]: # Write a python program to find below output:-


#Input:- 'peter piper picked a peck of pickled peppers.'
#Output:- 'retep repip dekcip a kcep fo delkcip .sreppep'

my_str='peter piper picked a peck of pickled peppers.'

res=' '.join(my_str[::-1].split()[::-1])
print(res)

retep repip dekcip a kcep fo delkcip .sreppep

27 eval()
[225]: # It evaluates the type

[227]: a=eval('5')
print(a,type(a))

5 <class 'int'>

[228]: a=eval('5.5')
print(a,type(a))

5.5 <class 'float'>

[229]: a=eval('[5]')
print(a,type(a))

[5] <class 'list'>

[230]: # Create a list heterogenous elements by taking the input from the user

[241]: a=eval(input('Enter a value- '))


print(a,type(a))

Enter a value- 5.5


5.5 <class 'float'>

[ ]:

17

You might also like