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

Class 13 List Methods

1. The document discusses list methods in Python, specifically slicing and list comprehension. 2. Slicing allows fetching sublists from a list by specifying start and stop indices. List comprehension provides a concise way to create lists using for loops. 3. Various examples demonstrate slicing lists with positive and negative indices, as well as creating lists from other iterables like strings, tuples, dictionaries using list(), and from ranges using list comprehension.

Uploaded by

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

Class 13 List Methods

1. The document discusses list methods in Python, specifically slicing and list comprehension. 2. Slicing allows fetching sublists from a list by specifying start and stop indices. List comprehension provides a concise way to create lists using for loops. 3. Various examples demonstrate slicing lists with positive and negative indices, as well as creating lists from other iterables like strings, tuples, dictionaries using list(), and from ranges using list comprehension.

Uploaded by

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

Class_13_List_Methods

May 13, 2023

1 Slicing
• Fetching a sublist from a list is known as slicing.

[3]: # lst[start_index:stop_index:step_size]
# Stop_index is excluded
# Step_size is 1 by default

[2]: lst=['Python',True, {1:100,2:200},None, 50,(1,2,3),10+20j, False, 5.5]


print(lst,type(lst))

['Python', True, {1: 100, 2: 200}, None, 50, (1, 2, 3), (10+20j), False, 5.5]
<class 'list'>

[5]: # Fetch the first four elements indexs-[0,1,2,3,4] 5


print(lst[0:5:1])
print(lst[0:5])

['Python', True, {1: 100, 2: 200}, None, 50]


['Python', True, {1: 100, 2: 200}, None, 50]

[10]: # Reverse the list [-1,-2,-3,-4,-5,-6,-7,-8,-9] -10


print(lst[-1:-10:-1])
print(lst[-1:-len(lst)-1:-1])

[5.5, False, (10+20j), (1, 2, 3), 50, None, {1: 100, 2: 200}, True, 'Python']
[5.5, False, (10+20j), (1, 2, 3), 50, None, {1: 100, 2: 200}, True, 'Python']

[9]: -len(lst)-1

[9]: -10

2 When step is +ive


• The start is 0 by default
• The stop is len(lst) by default

1
3 When the step is -ive
• Start is -1 by default.
• Stop is -len(lst)-1 by default.

[12]: lst

[12]: ['Python', True, {1: 100, 2: 200}, None, 50, (1, 2, 3), (10+20j), False, 5.5]

[29]: # Firt four elements


print(lst[:4:1])
print(lst[:4])

['Python', True, {1: 100, 2: 200}, None]


['Python', True, {1: 100, 2: 200}, None]

[20]: len(lst)

[20]: 9

[38]: print(lst[0:9])
print(lst[0:len(lst):1])
print(lst[::])

['Python', True, {1: 100, 2: 200}, None, 50, (1, 2, 3), (10+20j), False, 5.5]
['Python', True, {1: 100, 2: 200}, None, 50, (1, 2, 3), (10+20j), False, 5.5]
['Python', True, {1: 100, 2: 200}, None, 50, (1, 2, 3), (10+20j), False, 5.5]

[27]: # lst[9]

[34]: # Reverse the list

print(lst[-1:-len(lst)-1:-1])
print(lst[::-1])

[5.5, False, (10+20j), (1, 2, 3), 50, None, {1: 100, 2: 200}, True, 'Python']
[5.5, False, (10+20j), (1, 2, 3), 50, None, {1: 100, 2: 200}, True, 'Python']

[40]: lst[:5000]

[40]: ['Python', True, {1: 100, 2: 200}, None, 50, (1, 2, 3), (10+20j), False, 5.5]

[42]: # lst[50]

[43]: print(lst[0:5:-1])

[]

[44]: lst

[44]: ['Python', True, {1: 100, 2: 200}, None, 50, (1, 2, 3), (10+20j), False, 5.5]

2
[50]: # [5.5,(1,2,3),{1:100,2:200}]
# [(10+20j),50,{1:100,2:200},'Python']

[53]: print(lst[::-3])
print(lst[-3::-2])

[5.5, (1, 2, 3), {1: 100, 2: 200}]


[(10+20j), 50, {1: 100, 2: 200}, 'Python']

4 How to create a list

5 Case_1
• When we already know the elements

[54]: lst=[True, 'Python', 10,20, 5.2]


print(lst,type(lst))

[True, 'Python', 10, 20, 5.2] <class 'list'>

6 Case_2
• Using list()

[56]: # list(iterable)g
# list() takes an iterable as an argument and returns a list

[57]: # Iterable- String, List, Tuple, Dictionary, Set, Frozenset, Range

[62]: my_str='Python'
print(my_str,type(my_str))
print(len(my_str))
print()

lst=list(my_str)
print(lst,type(lst))
print(len(lst))

Python <class 'str'>


6

['P', 'y', 't', 'h', 'o', 'n'] <class 'list'>


6

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

lst=list(t)

3
print(lst,type(lst))

(10, 20, 30, 40, 50) <class 'tuple'>


[10, 20, 30, 40, 50] <class 'list'>

[71]: d={1:100,2:200,3:300,4:400}
print(d,type(d))

lst=list(d)
print(lst,type(lst))

lst=list(d.values())
print(lst,type(lst))

{1: 100, 2: 200, 3: 300, 4: 400} <class 'dict'>


[1, 2, 3, 4] <class 'list'>
[100, 200, 300, 400] <class 'list'>

[73]: s={True, 50, 'Python','Hello'}


print(s,type(s))

lst=list(s)
print(lst,type(lst))

{'Python', True, 50, 'Hello'} <class 'set'>


['Python', True, 50, 'Hello'] <class 'list'>

[76]: f=frozenset({10,20,30,40,50,60})
print(f,type(f))

lst=list(f)
print(lst,type(lst))

frozenset({50, 20, 40, 10, 60, 30}) <class 'frozenset'>


[50, 20, 40, 10, 60, 30] <class 'list'>

[82]: r=range(1,5)
print(r,type(r))

lst=list(r)
print(lst,type(lst))

lst=list(range(5))
print(lst,type(lst))

range(1, 5) <class 'range'>


[1, 2, 3, 4] <class 'list'>
[0, 1, 2, 3, 4] <class 'list'>

4
7 Case_3
• By taking the input from the user

[84]: lst=list(input('Enter some values- '))


print(lst,type(lst))

Enter some values- 123


['1', '2', '3'] <class 'list'>

[85]: list('123')

[85]: ['1', '2', '3']

[86]: lst=list(input('Enter some values- '))


print(lst,type(lst))

Enter some values- Hello Python


['H', 'e', 'l', 'l', 'o', ' ', 'P', 'y', 't', 'h', 'o', 'n'] <class 'list'>

[87]: list('Hello Python')

[87]: ['H', 'e', 'l', 'l', 'o', ' ', 'P', 'y', 't', 'h', 'o', 'n']

[88]: # Output- ['Hello','Python']


# Output- [10,20,30,40]

[90]: s=input('Enter the values- ')


lst=s.split()
print(lst)

Enter the values- Hello Python


['Hello', 'Python']

[91]: s=input('Enter the values- ')


lst=s.split()
print(lst)

Enter the values- 10 20 30 40 50


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

[92]: '10 20 30 40 50'.split()

[92]: ['10', '20', '30', '40', '50']

8 eval()
• It evaluates the type of the value.

[93]: # Syntax- eval('value')

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

10 <class 'int'>

[95]: a=eval('2.5')
print(a,type(a))

2.5 <class 'float'>

[99]: a=eval('"Hello"')
print(a,type(a))

Hello <class 'str'>

[97]: "Hello"

[97]: 'Hello'

[101]: abc=10
abc

[101]: 10

[103]: a=eval('[10,20,30,40]')
print(a,type(a))

[10, 20, 30, 40] <class 'list'>

[111]: a=eval(input('Pass a value- '))


print(a,type(a))

Pass a value- [10,20,30,40]


[10, 20, 30, 40] <class 'list'>

[105]: input()

55

[105]: '5'

[106]: eval('5')

[106]: 5

[109]: eval('Hello')

---------------------------------------------------------------------------
NameError Traceback (most recent call last)
~\AppData\Local\Temp\ipykernel_15708\3378726434.py in <module>
----> 1 eval('Hello')

6
<string> in <module>

NameError: name 'Hello' is not defined

[112]: lst=[]
for i in range(5):
a=eval(input('Enter a value- '))
lst=lst+[a]
print(lst)

Enter a value- 10
Enter a value- 2.5
Enter a value- True
Enter a value- "Python"
Enter a value- 10+20j
[10, 2.5, True, 'Python', (10+20j)]

[113]: lst=[]
for i in range(5):
a=eval(input('Enter a value- '))
lst=lst+[a] # or lst.append(a)
print(lst)

Enter a value- 40
Enter a value- 50
Enter a value- "Hello"
Enter a value- [1,2,3,4]
Enter a value- (10,20,30)
[40, 50, 'Hello', [1, 2, 3, 4], (10, 20, 30)]

[114]: lst

[114]: [40, 50, 'Hello', [1, 2, 3, 4], (10, 20, 30)]

[116]: for i in lst:


print(i,type(i))

40 <class 'int'>
50 <class 'int'>
Hello <class 'str'>
[1, 2, 3, 4] <class 'list'>
(10, 20, 30) <class 'tuple'>

[117]: lst=[]
for i in range(5):
a=input('Enter a value- ')
lst=lst+[a] # or lst.append(a)

7
print(lst)

Enter a value- 10
Enter a value- 20
Enter a value- Hello
Enter a value- (1,2,3,4,5)
Enter a value-
['10', '20', 'Hello', '(1,2,3,4,5)', '']

[119]: for i in lst:


print(i,type(i))

10 <class 'str'>
20 <class 'str'>
Hello <class 'str'>
(1,2,3,4,5) <class 'str'>
<class 'str'>

9 Case_4
• By using list comprehension
• List comprehension is the easier way to create a list using loop

[120]: # Syntax- [for loop]


# [value for variable in iterable]

[121]: # for variable in iterable


for i in 'Python':
print(i)

P
y
t
h
o
n

[124]: lst=[10 for i in 'Python']


print(lst)

[10, 10, 10, 10, 10, 10]

[127]: lst=[i for i in 'Python']


print(lst)

['P', 'y', 't', 'h', 'o', 'n']

[144]: # Create a list of even numbers from 2 to 20 using list comprehension

8
lst=[]

for i in range(2,21,2):
lst+=[i] # lst=lst+[i]
print(lst)
# print(lst)

[2, 4, 6, 8, 10, 12, 14, 16, 18, 20]

[141]: lst=[]
lst+=[2]
print(lst)

lst+=[4]
print(lst)

lst+=[6]
print(lst)

[2]
[2, 4]
[2, 4, 6]

[150]: lst=[i for i in range(2,21,2)]


print(lst)

[2, 4, 6, 8, 10, 12, 14, 16, 18, 20]

[151]: # Create a list of letters from A to Z using list comprehension

[154]: print(ord('A'))
print(ord('Z'))

65
90

[159]: print(chr(65))
print(chr(66))
print(chr(89))
print(chr(90))

A
B
Y
Z

[164]: for i in range(ord('A'),ord('Z')+1):


print(i,chr(i))

65 A

9
66 B
67 C
68 D
69 E
70 F
71 G
72 H
73 I
74 J
75 K
76 L
77 M
78 N
79 O
80 P
81 Q
82 R
83 S
84 T
85 U
86 V
87 W
88 X
89 Y
90 Z

[166]: lst=[]

for i in range(65,91):
lst+=[chr(i)]
print(lst)

['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P',
'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']

[169]: lst=[chr(i) for i in range(65,91)]


print(lst)

['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P',
'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']

[172]: # Create a list of the squares of the numbers from 1 to 10


lst=[]
for i in range(1,11):
# print(i**2)
lst+=[i**2]
print(lst)

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

10
[178]: lst=[i**2 for i in range(1,11,1)]
print(lst)

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

[177]: # [value for loop condition (optional)]

[181]: # Create a list of the numbers that are divisible by 2 but not divisible by 5␣
↪from 1 to 50

lst=[]
for i in range(1,51):
if i%2==0 and i%5!=0:
# print(i)
lst+=[i]
print(lst)

[2, 4, 6, 8, 12, 14, 16, 18, 22, 24, 26, 28, 32, 34, 36, 38, 42, 44, 46, 48]

[183]: lst=[i for i in range(1,51) if i%2==0 and i%5!=0]


print(lst)

[2, 4, 6, 8, 12, 14, 16, 18, 22, 24, 26, 28, 32, 34, 36, 38, 42, 44, 46, 48]

[184]: # Create a list that has the squares of the even numbers and the cubes of the␣
↪odd numbers using list comprehension

# Output- [1,4,,27,16,125,36,343,64,729,100]

[192]: lst=[]

for i in range(1,11):
if i%2==0:
print(i**2)
lst+=[i**2]
else:
print(i**3)
lst+=[i**3]
print(lst)

1
4
27
16
125
36
343
64
729
100
[1, 4, 27, 16, 125, 36, 343, 64, 729, 100]

11
[193]: # [ternary operator for loop]

[195]: i=3
i**2 if i%2==0 else i**3

[195]: 27

[196]: lst=[i**2 if i%2==0 else i**3 for i in range(1,11)]


print(lst)

[1, 4, 27, 16, 125, 36, 343, 64, 729, 100]

[197]: lst=[eval(input('Enter a value- ')) for i in range(5)]


print(lst)

Enter a value- 10
Enter a value- 20
Enter a value- 'Helo'
Enter a value- 2.5
Enter a value- (1,2,3,4,5)
[10, 20, 'Helo', 2.5, (1, 2, 3, 4, 5)]

[198]: # exp_1 if condition else exp_2

[201]: [i**2 if i%2==0 else i**3 for i in range(1,11)]

[201]: [1, 4, 27, 16, 125, 36, 343, 64, 729, 100]

[202]: # Note- if condition after the loop


# if...else.. before the loop

10 List methods
[203]: lst=[10,20,30,40,50]
print(dir(lst))

['__add__', '__class__', '__class_getitem__', '__contains__', '__delattr__',


'__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__',
'__getattribute__', '__getitem__', '__gt__', '__hash__', '__iadd__', '__imul__',
'__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__',
'__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__',
'__reversed__', '__rmul__', '__setattr__', '__setitem__', '__sizeof__',
'__str__', '__subclasshook__', 'append', 'clear', 'copy', 'count', 'extend',
'index', 'insert', 'pop', 'remove', 'reverse', 'sort']

[204]: # 'append', 'clear', 'copy', 'count', 'extend', 'index', 'insert', 'pop',␣


↪'remove', 'reverse', 'sort'

12
11 append()
• It adds the element at the end of the list

[205]: # lst.append(value)

[212]: lst=[10,20,30]
print(lst)

lst.append(100)
print(lst)

lst.append('Python')
print(lst)

lst.append((1,2,3,4,5))
print(lst)

lst.append(0.25)
print(lst)

lst.append({2,5})
print(lst)

[10, 20, 30]


[10, 20, 30, 100]
[10, 20, 30, 100, 'Python']
[10, 20, 30, 100, 'Python', (1, 2, 3, 4, 5)]
[10, 20, 30, 100, 'Python', (1, 2, 3, 4, 5), 0.25]
[10, 20, 30, 100, 'Python', (1, 2, 3, 4, 5), 0.25, {2, 5}]

[213]: lst=[]

for i in range(1,11):
if i%2==0:
# print(i**2)
lst.append(i**2)
else:
# print(i**3)
lst.append(i**3)
print(lst)

[1, 4, 27, 16, 125, 36, 343, 64, 729, 100]

12 extend()
• It takes an iterable as an argument.
• It adds the elements of the iterable to the list one by one

13
[214]: # lst.extend(iterable)

[216]: lst=[10,20,30]
print(lst)

lst.extend('Python')
print(lst)

[10, 20, 30]


[10, 20, 30, 'P', 'y', 't', 'h', 'o', 'n']

[217]: lst=[10,20,30]
print(lst)

lst.append('Python')
print(lst)

[10, 20, 30]


[10, 20, 30, 'Python']

[218]: lst=[10,20,30]
print(lst)

lst.append((5,5,5))
print(lst)

[10, 20, 30]


[10, 20, 30, (5, 5, 5)]

[219]: lst=[10,20,30]
print(lst)

lst.extend((5,5,5))
print(lst)

[10, 20, 30]


[10, 20, 30, 5, 5, 5]

[220]: # lst+=iterable # Internally extend method is applied

[227]: lst=[10,20,30]

lst+={1:100,2:200}.values()
print(lst)

[10, 20, 30, 100, 200]

[231]: lst=[10,20,30]
lst=lst+['Python']
lst

14
[231]: [10, 20, 30, 'Python']

[232]: # lst=lst+[] - Concatenation


# lst+=iterable - extend()

[237]: lst=[]
lst=lst+['Hello']
print(lst)

['Hello']

[238]: lst=[]
lst+='Hello'
print(lst)

['H', 'e', 'l', 'l', 'o']

[239]: a = 'Python'
b = ''

#Apply logical opereators (and, or & not) on above string values and observe␣
↪the output.

print(a and b)
print(b and a)
print(a or b)
print(b or a)
print(not a)
print(not b)

Python
Python
False
True

[241]: bool('Python'),bool('')

[241]: (True, False)

[243]: a and b

[243]: ''

[ ]: 'a' and 'b'

[245]: bool('a'),bool('b')

[245]: (True, True)

15
[246]: True and True

[246]: True

[247]: 'a' and 'b'

[247]: 'b'

[249]: False and True

[249]: False

[251]: bool(0+0j), bool(5j)

[251]: (False, True)

[252]: 0+0j

[252]: 0j

[253]: str1 = 'Python'


str2 = 'Python'
#Compare str1 and str2 and print True using comparison operator
#Compare str1 and str2 and print True using equality operator
#Compare str1 and str2 and print False using equality operator
#Compare str1 and str2 and print False using comparison operator

print(str1<=str2)
print(str1>=str2)
print(str1==str2)
print(str1!=str2)

True
True
True
False

[259]: str1 = 'python'


str2 = 'Python'
#Compare str1 and str2 and print True using comparison operator
#Compare str1 and str2 and print True using equality operator
#Compare str1 and str2 and print False using equality operator
#Compare str1 and str2 and print False using comparison operator

print(str1>=str2)
print(str1<=str2)
print(str1==str2)
print(str1!=str2)

16
True
False
False
True

[ ]: my_str = "Although 8 that way may not be obvious at first unless you're Dutch"

#Write the code to get the total count of 't' in above string. Use find() and␣
↪index() method.

17

You might also like