-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathpython notes
More file actions
2304 lines (1905 loc) · 52.7 KB
/
python notes
File metadata and controls
2304 lines (1905 loc) · 52.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
python : von guido rossum ->
class HelloWorld{
pubic static void main(String args[]){
int a=10;
int b=20;
int c=a+b;
System.out.println("sum is : " c);
}
}
a,b=10,20
print("sum is : " (a+b))
1. simple and easy to learn
2. case sensitive
3. freeware and opensource --> Jython (python and java)
4. high level
5. platform independent or architectural nuetral or portable
6. dynamically typed language
7. oops language
8. interpreted language --> shell scripting, groovy scripting
9. robust --> extensible libraries
10. embedded
=========================================
pycharm, intellijidea, vistudio, atom --> IDE's
==============================================
Identifiers : class, object, function
naming convensions : a-z, A-Z, 0-9 and _
_name --> private identifier
__name ---> strongly private identifier
__name__ --> language specific identifier
=====================================================
Reserved words in python : 33
if else elif for while True False None and or not is break continue, case, return, try, except, in, yield, finally, raise, assert
import from as class def pass global nonlocal lambda del with
====================================================================
Data types : python is dynamically typed language. no need to define data type explicitly
implicit data types : 14
=========================
int float complex bool str bytes bytearray range list tuple set frozenset dict None
====================================================================================
int : integer values, default numbering system is decimal numbering system
float : fractional numbers
complex : stores both real and imaginary values. eg: 2+3j
bool : True, False
str : > no char type
> using '', ""
> multiline strings are defined by ''' ''', """ """
> using slice operator, we can perform string operations easily
> string-name[begin:end:step]
type concersion: type casting or type coersion (convert one type to another type )
=====================================================================================
defacult type conversion functions in python are : int(), float(), complex(), str() and bool()
> int(), float() : convert from any type to int,float except complex
> complex() : convert from any type to complex except string
> bool() : convert any type to boolean including complex
String formatting :
===================
> using repition operator '{}'
bytes and bytearray datatype : range is 0 to 255, used for to process image or video file in DIP applications
===============================
> bytes is immutable
> bytearray is mutable
ex : x=[10,20,30]
y=bytes[x]
b[0]=100 --> not allowed to insert
z=byetarray[x]
b[0]=100 --> allowed to insert
***list data type :
===================
To represent group of objects as a single entity, where insertion order required to preserve and duplicates are allowed
> list defination, l=[]
> scalable / growable
> mutable
> insertion order is preserved
> duplicates are allowed
> slicing is possible
> both homogeneous and heterogenious objects are allowed
> ex : l=[1,2.3,"Ram"]
tuple : similar to list except immutability
============================================
> tuple defination : t=()
> read only version of list
> slicing is possible
> not scalable
> ex : t=(10,20,30)
set :
=====
> set defination, *** s=set() / s={} --> not allowed ***
> elements are enclosed in {}
> group of objects as a single entity
> duplicates are not allowed
> insertion order is not preserved
> slicing is not possible
> Scalable
> Mutable
> both homogeneous and heterogenious objects are allowed
> ex : s={10,20,30}
frozenset : similar to set except immutability
==============================================
> ex: s={10,20,30}
fs=frozenset(s)
fs.add(40) --> not applicable for frozenset
*** dictionary : used to store key and value pairs
===================================================
> Mutable
> order is not preserved
> no slicing feature
> dict defination, d={}
> ex : d={ 1: 'apple', 2: 'orange'}
range() :
=========
> elements in range type is immutable
> slicing is allowed
> ex : r=range(10)
print(type(r))
> ex: r=range(10)
for i in r[2:8]:
print(i)
> ex: for i in range(0,101,5):
print(i)
None : No datatype, not pointing to any object
==============================================
> ex : def m1():
a=10
print("Hello")
f1()
print(f1())
Escape characters :
===================
\n, \t, \r, \b, \f --> formfeed, \v --> vertical tab
\' -> single quote
\" -> double quote
\\ -> back slash
ex : s= 'the book \'python\' is very easy'
constants :
===========
> recommended to define constants using uppercase letters
> ex : MAX_VALUE=10
Operators :
===========
> arthmatic, relational or comparision, logical, bitwise, assignement operators, special operators
arithmatic operators : +,-,*,/,%,//,**
+ -> addition and concatanation
* -> multiplication and repetition
x/0,x//0,x%0 -> zero division error
relational operators : >, >=, <, <=
Equality operators : ==, !=
*** == is compares content
*** 'is' operator compares reference id
*** difference between '==' and 'is' operator ***
Logical operators : and, or, not
and : if x is False then returns x otherwise it returns y (True)
or : if x is True then it returns True otherwise returns y (False)
not : complement operation
Bitwise operators : &,|,^,~ (perform actions on only int and boolean values)
Shift operators : <<,>>,>>>
Assignement operators : +=,-=,*=,/=,%=, //=, **= (compound assignement operarors)
&=,|=,^=,>>=,<<=
Special operators :
***1. identity operators : is, is not
ex : l1=["One","Two","Three"]
l2=["One","Two","Three"]
print(l1 is l2)
print(l1 == l2)
print(l1 is not l2)
2. Membership operators : in, not in
ex ;
str1="leanring python is easy"
print('z' in str1)
print('easy' in str1)
print('d' not in str1)
***3. Ternary operator : reduces code
syntax : x=a if condition else b
ex : x=4 if 10>20 else 5
***WAP to read 2 numbers from the key board and print minimum value :
a=int(input("Enter 1st number : "))
b=int(input("Enter 1st number : "))
if a<b: | min=a if a<b else b | print(a if a<b else b)
print(a) | print(min) |
else | |
print(b) | |
*** Nested of ternary operator is possible :
ex :
a,b,c=10,20,30
x=a if a<b and a<c else b if b<c else c
ex :
a=int(input("Enter 1st number : "))
b=int(input("Enter 1st number : "))
print("a is greter than b" if a>b else "a is lessthan b" if a<b else "both are equal")
Operator precedence : priority operation
1 -> ()
2 -> **
3 -> ~,- (unary minus)
4 -> *,/,%,//
5 -> +,-
6 -> <<,>>,&,^,|,>,<,>=,<=,==,!=
7 -> =, +=, -=
8 -> is, is not, in, not in, not, and , or
ex : print((a+b)*c/d)
module : it is a group of vars,functions,classes
===================================================
group of modules -> packages
group of packages -> library
www.python.org
***math module : performs mathematical operations
> using import keyword we can use math module
ex :
import math
print(math.sqrt(4))
print(math.pi)
> we can create alias for any module
ex:
import math as m
print(m.sqrt(4))
print(m.pi)
> use specific functions from madule
ex:
from math import * | sqrt,pi
print(sqrt(4))
print(pi)
> we can create aliases for methods in modules
ex:
from math import sqrt as a, pi as b
print(a(4))
print(b)
important functions in math module :
sqrt(), ceil(), floor(), pow(), factorial(), trunc(), gcd(), sin(), cos(), tan(), ...
*** WAp to read radius of circle from the keyboard and print its area :
from math import pi
r=int(input("enter radius: "))
print("area is : ", pi*r**2)
Input and Output statements :
=============================
** How to read input dynamically from the keyboard
for python2, 1. raw-input() and 2. input()
** It reads only string type.
** Typecasting is required while reading input from keyboard.
for python 3, only input() is available
Ex:
name=input('Enter name : ')
mobile=int(input('Enter your mobile number : '))
height=float(input("Enter your height : '))
martialstatus=eval(input('Enter martial status [True/False] : '))
print('You entered : ', name)
print('Your mobile number is : ', mobile)
print('Your height in feets and inches : ', height)
print('Your martial status is : ',martialstatus)
***How to read multiple values from keyboard in a single line : (List comprehension)***
----------------------------------------------------------------------------------------
print(input("Enter 2 numbers : ")) ---> "10 20" string type
print(input("Enter 2 numbers : ").split()) --> [ '10','20'] --> list of strings
print([int(x) for x in input("Enter 2 numbers : ").split()]) --> list of integers
Ex: Add two numbers from keyboard
a,b=[int(x) for x in input("Enter 2 numbers : ").split(',')]
print('Sum is : ',a+b)
*** eval() : converts string to corresponding datatype
======================================================
ex:
x=eval("10+20+30")
print(x)
ex:
x=eval(input("Enter any expression : ")) --> 10+20*30/4 or Raja*3
print(x)
*** command line arguments :
============================
-> We can use 'argv' to use commandline arguments
-> argv -> is list type will be avaialble in 'sys' module
ex:
from sys import argv
print(type(argv))
print("no.of commandline arguments: ", len(argv))
print("The list of commandline arguments: ",argv)
print("commandline arguments one by one: ")
for i in argv:
print(i)
Run : py test.py 10 20 30
-------------------------
ex:
from sys import argv
sum=0
args=argv[1:]
for i in args:
n=int(i)
sum=sum+i
print("The sum is : ",sum)
ex:
from sys import argv
args=argv[1]
print(args)
print(argv[1]+argv[2]) # test with string args
print(2*argv[1])
print(int(argv[1])+int(argv[2])) # test with int args
print(argv[100]) # will get index out of range error
output statements :
===================
print() :
--------
> normal blank print method is print()
> we can use escape characters (\n,\t ...)
> we can use +(concatanation) and *(repetition) operators
> We can pass with variable no.of args :
ex: a,b,c,d=10,2,3,4
print("The result is : ", a,b,c,d)
print("The result is : ", a,b,c,d,sep=',') -> using sep attribute
print("The result is : ", a,b,c,d,sep=':')
print(a, end=' ') -> using end attribute, useful while creating puzzles
print(b, end=' ')
print(c, end=' ')
print(d)
> We can used print objects : l=[10,20]
print(l)
> We can print string and variable list :
str1="Raja"
age=29
print("Hello, ", str1, "Your age is ",age)
> We can use with formatted string : (%i,%d -> int %f -> float %s -> string )
a,b,c=10,20,30
print("a value is %d", %a)
print("b value is %d and c value is %d", %(b,c))
> We can use replacement operator :
ex:
name='Raja'
salary=50
country='India'
print("Hello {} your salary is {} you are from {}".format(name,salary,country))
print("Hello {0} your salary is {1} you are from {2}".format(name,salary,country))
print("Hello {a} your salary is {b} you are from {c}".format(a=name,b=salary,c=country))
flow control :
==============
Selection statements : if, if-else, if-elif-else
Iterative statements : for, while
Transfer statements : break, continue, pass and return
Note : no switch and dowhile
Selection statements :
-----------------------
if :
if <condition>:
statements
if-else :
if <condition>:
statements
else
default statements
if-elif-else : replacement of switch
if <condition>:
statements
elif <condition>
statements
elif <condition>
statements
.
.
.
else
default statements
Ex :
book=input('Enter your favourite book : ')
if book=='python':
print("Your favourite book is %s",%book)
elif book=='java':
print("Your favourite book is %s",%book)
else
print("Your favourite book is DevOps")
Ex: Largest num of three numbers
n1=int(input("enter first number : ")
n2=int(input("enter second number : ")
n3=int(input("enter third number : ")
if n1>n2 and n1>n3:
print(n1,"is greter than",n2,"and",n3)
elif n2>n3:
print(n2,"is greter than",n1,"and",n3)
else
print(n3,"is greter than",n1,"and",n2)
using list comprehension and ternary operator :
-----------------------------------------------
n1,n2,n3=[int(x) for x in input("Enter three numbers : ").split()]
print(n1 if n1>n2 and n1>n3 else n2 if n2>n3 else n3)
Ex: to read single digit number from the keyboard and print its value in english words
n=int(input("Enter any number between 0 to 9 : ")
if n==0:
print("Zero")
elif n==1:
print("One")
.
.
.
else
print("Enter numbers between 0 to 9 only")
Iterative statements : for and while loops
==========================================
for loop :
----------
for i in <iterable item> or <string>:
statements
Ex:
for i in [10,20,30]:
print(i)
for i in "This is python programming language":
print(i)
Ex:
s=input("Enter any string : ")
i=0
for x in s:
print("The character at {} index is : {}".format(i,x))
i+=1
Ex:
for x in range(10):
print(x)
# asending order
for x in range(1,11):
print(x)
# odd numbers
for x in range(1,11,2):
print(x)
# even numbers
for x in range(0,11,2):
print(x)
# decending order`
for x in range(11,1,-1):
print(x)
# add list of numbers from the keyboard
list=(input("Enter any list of numbers : ").split())
sum=0
for i in list:
x=int(i)
sum+=x
print("Sum of given list of numbers are {}".format(sum))
while loop :
============
while <condition>: --> as long as condition is true, its body repetedly executes
<body>
Ex:
x=1
while x<=10:
print(x)
x+=1
Ex: Sum of first n numbers
n=int("Enter any number : ")
x=1
sum=0
while x<=n: | while x in range(n+1)
sum+=x
x+=1
print(sum)
Ex: prompt user to enter some same until entering your name
name=''
while name!='Raja':
name=input('Enter name : ')
print('Thank you for your confirmation')
Ex: infinite loops
i=0
while True:
print("Hello; ",i)
i+=1
Nested loops :
==============
Ex:
for i in range(4):
for j in range(4):
print("i={} and j={}".format(i,j))
Ex:
n=int(input("Enter the no.of rows: "))
for i in range(n):
for j in range(n):
print('*',end='')
print()
# using single for loop
for i in range(n):
print('* '*n)
Ex:
n=int(input("Enter the no.of rows: "))
for i in range(1,n+1):
for j in range(n):
print(i,end=' ')
print()
Ex: right angle triangle pattern
n=int(input("Enter the no.of rows: "))
for i in range(1,n+1):
print('* '*i)
Ex: equilateral triangle pattern
n=int(input("Enter the no.of rows: "))
for i in range(1,n+1):
print(' '*(n-i), end=' ')
print('* '*i)
Transfer statements :
=====================
1. break : to break/stop execution in side the loop execution/iteration
=======================================================================
Ex:
for i in range(10):
if i==3:
print("Thank you")
break
print(i)
print("end of loop")
Ex:
cart=[10,200,300,500,1000]
for i in cart:
if i>300:
print("Thank you for shopping")
break
print("placed",i)
2. continue : To skip current iteration and to continue next iteration we use continue statement
=============
Ex:
for i in range(10):
if i%2==0:
continue
print(i)
Ex:
cart=[10,200,300,500,1000]
for i in cart:
if i>300:
print("Thank you for shopping")
continue
print("placed",i)
Ex:
num=[10,200,0,500,0]
for i in num:
if i==0:
print("Avoid zero division error")
continue
print("100/{}={}".format(i,100/i))
Ex: loops with else block
# if for loop without break executed then else block will be executed
cart=[10,20,30,40]
for i in cart:
if i>300:
print("Thank you for shopping")
break
print("placed",i)
else:
print("All items are placed successfully")
pass statement:
==============
> if we want pass empty task without error, we should use 'pass' statement
Ex:
if True: pass
print('passed')
class Student:
pass
class Person:
def read():
pass
class Teacher:
def read(self):
print('python'+'java')
def m1(): pass
for i in range(100):
if i%9==0:
print(i)
else: pass
del keyword:
============
> After using a variable. If that variable is no longer used, then we can destroy that variable using 'del' keyword
Ex:
x=10
print(x)
del x
print(x)
*** difference between None and del :
None : s=None -> then s will not point to any object
del: s='xyz'
del s -> then 's' variable and object will be deleted
*** String data type :
======================
> string objects are immutable
> '', "", ''' ''', """ """
> index
> slicing
> concatanation(+) and repetition (*)
> membership operators (in, not in)
> comparision operators (<,<=,>,>=,==,!=)
> string formating using replacement operators ({}) with format() and using formatted string (%i or %d for int, %f for float, %s for string)
> built-in functions :
len() -> to get length of string
find() -> to check substring is avaialble or not. returns 1st occurance of string index of substring. returns -1 if substring is not avaialble
ex: s="learning python is easy"
print(s.find('python'))
rfind() -> searches 1st occurance of substring in reverse direction
find(substring,begin,end) -> searches given substring in specified begin and end-1 index
index() -> same as find() except if substring is not available it returns "ValueError"
count(substring) and count(substring,begin,end) -> counting substrings in the given string
replace(oldstring,newstring) -> ***by creating new string objects we can replace old string with new string
***split(delimeter) -> we can split string using delimeter (space, ',','/',':'...). converting from string to substrings. returns list type object
Ex: s='30/12/1981'
print(s.split('/')
***join() -> used to join group of substrings with a separator. Syntax : string=separator.join(group-of-substrings)
Ex: l=['30','December','1981']
print('/'.join(l))
upper() -> used to convert string in to uppercase letters
lower() -> used to convert string in to lowercase letters
swapcase() -> L->U and U->L
title() -> first letters are capital
capitalize() -> Only first letter is capital
startswith(substring) -> returns True if string is starts with substring
endswith(substring) -> returns True if string is ends with substring
isalnum() -> returns True is alpha numeric character is found in the string
isalpha() -> returns True is alphabetic character is found in the string
isdigit() -> returns True is numeric character is found in the string
islower() -> True if lower
isupper() -> True if upper
istitle() -> True if tiltle characters
isspace() -> True if spaces
Important programs for to perform string operations :
=====================================================
1. To reverse given string :
# using slicing
s=input("Enter your name : ")
print(s[::-1])
# without slicing
s=input("Enter your name : ")
i=len(s)-1
rev_s=''
while i>=0:
rev_s+=s[i]
i=i-1
print(rev_s)
# using for loop
s=input("Enter your name : ")
i=len(s)-1
rev_s=''
for i in range(i,-1,-1):
rev_s+=s[i]
print(rev_s)
2. To reverse order of words :
s=input("Enter your name : ")
l=s.split()
print(l)
l1=[]
i=len(l)-1
while i>=0:
l1.append(l[i])
i=i-1
print(l1)
output=' '.join(l1)
print(output)
3. To reverse internal content of each words
s=input("Enter your name : ")
l=s.split()
l1=[]
for i in range(len(l)): # for i in l:
s1=l[i] # l1.append(s1[::-1])
l1.append(s1[::-1]) # output=' '.join(l1)
print(l1) # print(output)
output=' '.join(l1)
print(output)
4. Write program ro print characters in odd position and even positions
#using slicing
s=input("Enter String : ")
print("char's in even position : ", s[0::2])
print("char's in odd position : :, s[1::2])
#without slicing
i=0
print("chars in even position are : ")
while i<len(s):
print(s[i], end=',')
i+=2
print()
print("chars in odd position are : ")
i=1
while i<len(s):
print(s[i], end=',')
i+=2
5. Merging chars of two strings in to a single string by taking characters alternatively
s1=input("Enter string 1 : ")
s2=input("Enter String 2 : ")
output=''
i,j=0,0
while i<len(s1) or j<len(s2):
output=output+s1[i]
i+=1
output+=s2[j]
j+=1
print(output)
6. i/p: B4A1D3 o/p: ABD134
s=input("Enter string 1 : ")
s1=s2=output=''
for x in s:
if x.isalpha():
s1=s1+x
else:
s2=s2+x
print(''.join([s1,s2]))
print(s1+s2)
print(''.join(sorted(s1))+''.join(sorted(s2)))
7. i/p: a1b2c3 o/p: abbccc
s=input("Enter string 1 : ")
output=''
for x in s:
if x.isalpha():
output=output+x
previous=x
else:
output=output+previous*(int(x)-1)
print(output)
8. i/p: a4k3b2 o/p:aeknbd
s=input("Enter string 1 : ")
output=''
for x in s:
if x.isalpha():
output=output+x
previous=x
else:
## for to understand, i/p=a4k3b2 expectedd o/p=aeknbd
## ord(char) returns unicode while chr(unicode) returns char
output=output+chr(ord(previous)+int(x)) ## a=a+chr(97+4) => ae...
print(output)
9. i/p=ABCABCAAABCAD O/P=ABCD
s=input("Enter string : ")
output=''
for x in s:
if x not in output:
output+=x
print(output)
10. i/p= ABAAABBCCDAABBBBCCCCCCCCDDDDDDDDDDDDDDDD o/p= A->6 B->7 C->10 D->17
s=input("Enter string : ")
d={}
for x in s:
if x in d.keys():
d[x]+=1
else:
d[x]=1
print(d)
for k,v in d.items():
print('{}={} times'.format(k,v))
list data type :
===============
> Group of elements as a single entity where insertion order is preserved and duplicates are allowed
> Mutable
> Scalable
> homogeneous and heterogenious objects are allowed
> slicing is applicable
list creation :
---------------
> l=[]
> dynamically creating list : l=eval(input("Enter list : "))
> list(sequence) -> used to create list with that sequence. l=list('Raja') -> l=['R','a','j','a'] or list(range(4)) or list(range(5,21)), list(range(5,101,5))
> spilt() converts ctring in to list Ex: s=input('Enter string: ') l=s.split() print(l) print(type(l))
> list inside another list is called nested list. Ex: l=[1,2,[1,2,3]]
Accessing elements of the list :
--------------------------------
> two ways : (1) Using index and (2) Using slicing
Ex:
l=[1,2,[1,2,3]]
print(l[1]) #2
print(l[2][2]) #2
Ex:
l=[1,2,3]
i=0
while i<len(l):
print(l[i])
i+=1
or
l=[1,2,3]
for i in l:
print(i)
Ex :
l=[0,1,2,3,4,5,6,7,8,9]
for i in l:
# print even numbers
if i%2==0:
print(i)
# print odd numbers
if i%2==1:
print(i)
Ex:
l=['A','B','C','D','E','F','G','H','I']
i=0
n=len(l)
for i in range(n):
print('{} is avaialbleat positive index: {} and at negative index: {}'.format(l[i],i,i-n))
Important functions of list:
----------------------------
1. len() : returns length of given list, eg: n=len(l)
2. count() : returns no of occurances of each element in the list, eg: print(l.count('A'))
3. index() : returns 1st occurance of specified element. If it is not found, returns 'ValueError', eg : print(l.index('A'))
4. append() : To add an element to the list, eg : l=[]; l.append('Raja')
Ex :
l=[]
for i in range(101):
if i%10==0:
l.append(i)
print(l)
5. insert() : Insert element in the list at specified index
Ex:
l=[1,2,3]
l.insert(1,4)
print(l)
6. extend() : adding all elemenets of one list to the another list
Ex:
l1=[1,2,3]
l2=[4,5,6]
l1.extend(l2)
print(l1)
7. remove() : Uses to remove specific item from the list. Always removes first occurance, if an element presented multiple times in the list.
Ex:
l=[1,2,3,1]
l.remove(1)
print(l) # If specified value is not avaialble then it will get "Value Error".
8. pop() : Uses to remove last element from the list and returns that element.
Ex:
l=[1,2,3,4]
print(l.pop())
print(l)
9. del() : uses to delete the list.
Ex:
l=[1,2,3]
del(l)
print(l)
10. reverse() : To display elements of the list in reverse order.
Ex:
l=[1,2,3,4]
l.reverse()
print(l)
11. sort() : To sort all elements in a list. If we want to use sort() we must use homogeneous elements
Ex :
l=[1,4,2,3]
l.sort()
print(l)
l.sort(reverse=True)
print(l)
Aliasing and cloning of the list object :
-----------------------------------------
> Creating duplicate reference is called as Aliasing. Aliasing is also called as "Shallow copy (create duplicate)" If we change anything in duplicate variables. The original list get affected
To avoid this problem. we can clone original list using 1. slice operator and 2. using copy() method.
Ex:
x=[1,2,3]
y=x # Aliasing
print(id(x))
print(id(y))
y.insert(1,5)
print(x)