0% found this document useful (0 votes)
7 views27 pages

Python Variables and Data Types Guide

The document is a Python script that covers various fundamental concepts of Python programming, including variable assignment, data types, and string manipulation. It demonstrates how to create and manipulate variables, the importance of variable naming conventions, and the use of built-in functions for data types. Additionally, it explains the concept of global and local variables, as well as string methods and slicing techniques.
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)
7 views27 pages

Python Variables and Data Types Guide

The document is a Python script that covers various fundamental concepts of Python programming, including variable assignment, data types, and string manipulation. It demonstrates how to create and manipulate variables, the importance of variable naming conventions, and the use of built-in functions for data types. Additionally, it explains the concept of global and local variables, as well as string methods and slicing techniques.
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

11/30/25, 8:29 PM new learn.

py

new [Link]

1 #python variables
2 x=5
3 y="hello world"
4 print(x)
5 print(y)
6 print(x,y)
7 #casting
8 x=str(3)
9 y=int(3)
10 z=float(3)
11 print(x)
12 print(y)
13 print(z)
14 #getting the type of above code
15 print(type(x))
16 print(type(y))
17 print(type(z))
18 #variables are case sensitive
19 a=4
20 A="clark kent"
21 print(a)
22 print(A)
23 #Rules for Python variables:
24 # A variable name must start with a letter or the underscore character
25 # A variable name cannot start with a number
26 # A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9,
and _ )
27 # Variable names are case-sensitive (age, Age and AGE are three different variables)
28 # A variable name cannot be any of the Python keywords.
29
30 # for multi words variable names we can use
31 # 1. camel case
32 myVariableName="jake"
33 # 2. pascal case
34 MyVariableName="john"
35 # 3. snake case
36 my_variable_name="henry"
37 print(myVariableName)
38 print(MyVariableName)
39 print(my_variable_name)
40
41 # assign multiple values
42 # assigning many values to different variables
43 x,y,z= "orange","banana","cherry"
44 print(x)
45 print(y)
46 print(z)
47
48 # assigning one value to multiple variables
49 x=y=z="mango"
50 print(x)
51 print(y)
localhost:52376/178a6b89-515c-48d4-81b2-a951d8109a59/ 1/27
11/30/25, 8:30 PM new [Link]

52 print(z)
53
54 #Unpack a Collection
55 # If you have a collection of values in a list, tuple etc. Python allows you to extract
the values into variables. This is called unpacking.
56 # unpacking a list
57 fruits=["apple","kiwi","mango"]
58 x,y,z=fruits
59 print(x)
60 print(y)
61 print(z)
62 # python output variabeles
63 x="steven"
64 y="is"
65 z="moon knight"
66 print(x,y,z)
67 print(x+y+z)
68 print(x+" "+y+" "+z)
69
70 #For numbers, the + character works as a mathematical operator:
71 a=5
72 b=10
73 print(a+b)
74
75 #In the print() function, when you try to combine a string and a number with the +
operator, Python will give you an error:
76 # @ x=5
77 # @ y="john"
78 # @ print(x+y) # this will give an error
79
80 # >>the best way to output multiple variables in print function is to use comma, this
even works for different data types
81 x=5
82 y="john"
83 print(x,y) # this will not give an error and will give output like this ^^ 5 john ^^
84 #
85 #
86 # global variables
87 x="great"
88 def myfunc():
89 print("Python is " + x)
90 myfunc()
91
92 # If you create a variable with the same name inside a function, this variable will be
local, and can only be used inside the function. The global variable with the same name
will remain as it was, global and with the original value.
93 x = "awesome"
94 def myfunc():
95 x = "fantastic"
96 print("Python is " + x)
97 myfunc()
98 print("Python is " + x)
99
100 # The global Keyword

localhost:52376/178a6b89-515c-48d4-81b2-a951d8109a59/ 2/27
11/30/25, 8:30 PM new [Link]

101 # Normally, when you create a variable inside a function, that variable is local, and can
only be used inside that function.
102 # To create a global variable inside a function, you can use the global keyword.
103
104 # example
105 # If you use the global keyword, the varb=iable belongs to the global space.
106 def myfunc():
107 global x
108 x = "fabulous"
109 myfunc()
110 print("Python is " + x)
111
112 # Also, use the global keyword if you want to change a global variable inside a function.
113 # To change the value of a global variable inside a function, refer to the variable by
using the global keyword:
114 x = "extreme"
115 def myfunc():
116 global x
117 x = "cococolastic"
118 myfunc()
119 print("Python is " + x)
120
121 # python datatypes
122 # built-in Data Types
123
124 ## Text Type: str
125 ## Numeric Types: int, float, complex
126 ## Sequence Types: list, tuple,range
127 ## Mapping Type: dict
128 ## Set Types: set, frozenset
129 ## Boolean Type: bool
130 ## Binary Types: bytes, bytearray, memoryview
131 ## None Type: NoneType
132
133 # Setting the Data Type
134 # In Python, the data type is set when you assign a value to a variable:
135
136 ##Example Data Type
137 # → x = "Hello World" str
138 # → x = 20 int
139 # → x = 20.5 float
140 # → x = 1j complex
141 # → x = ["apple", "banana", "cherry"] list
142 # → x = ("apple", "banana", "cherry") tuple
143 # → x = range(6) range
144 # → x = {"name" : "John", "age" : 36} dict
145 # → x = {"apple", "banana", "cherry"} set
146 # → x = frozenset({"apple", "banana", "cherry"}) frozenset
147 # → x = True bool
148 # → x = b"Hello" bytes
149 # → x = bytearray(5) bytearray
150 # → x = memoryview(bytes(5)) memoryview
151 # → x = None NoneType
152

localhost:52376/178a6b89-515c-48d4-81b2-a951d8109a59/ 3/27
11/30/25, 8:30 PM new [Link]

153 # python numbers


154 # There are three numeric types in Python:
155 int
156 float
157 complex
158 x = 1
159 y = 2.8
160 z = 1j
161 print(type(x))
162 print(type(y))
163 print(type(z))
164
165 # Int, or integer, is a whole number, positive or negative, without decimals, of
unlimited length.
166
167 # Float, or "floating point number" is a number, positive or negative, containing one or
more decimals.
168 # Float can also be scientific numbers with an "e" to indicate the power of 10.
169 x = 35e3
170 y = 12E4
171 z = -87.7e100
172
173 print(type(x))
174 print(type(y))
175 print(type(z))
176
177 # Complex numbers are written with a "j" as the imaginary part:
178 x = 1 # int
179 y = 2.8 # float
180 z = 1j # complex
181
182 a = float(x)
183
184 b = int(y)
185
186 c = complex(x)
187 print(a)
188 print(b)
189 print(c)
190 print(type(a))
191 print(type(b))
192 print(type(c))
193
194 ## Note: You cannot convert complex numbers into another number type.
195
196 # Random Number
197 # Python does not have a random() function to make a random number, but Python has a
built-in module called random that can be used to make random numbers:
198 import random
199 print([Link](1,6))
200
201
202 # Python strings

localhost:52376/178a6b89-515c-48d4-81b2-a951d8109a59/ 4/27
11/30/25, 8:30 PM new [Link]

203 # Strings in python are surrounded by either single quotation marks, or double quotation
marks.
204 # 'hello' is the same as "hello"
205
206 # Multiline Strings
207 # You can assign a multiline string to a variable by using three quotes:
208
209
210 # Python strings
211 # Strings in python are surrounded by either single quotation marks, or double quotation
marks.
212 # 'hello' is the same as "hello"
213
214 # Multiline Strings
215 # You can assign a multiline string to a variable by using three quotes:
216 a ="""I will continue,
217 until i find a man that i can't defeat
218 Next time they shine your light in the sky, don't go to it."""
219 print(a)
220
221 # Strings are Arrays
222 # Like many other popular programming languages, strings in Python are arrays of unicode
characters.
223 #However, Python does not have a character data type, a single character is simply a
string with a length of 1.
224 # Square brackets can be used to access elements of the string.
225 c="Dark arises"
226 print(c[2])
227
228 # looping through a string
229 # Since strings are arrays, we can loop through the characters in a string, with a for
loop.
230
231 # loop through the letters in the following word
232 b="BayHabour"
233 for i in b:
234 print(i)
235
236 #
237 # String Length
238 j="chainsaw"
239 print(len(j))
240
241 ### check string
242 txt = "death is free"
243 print("free" in txt) # this will give output as True or False as per the correctness of
condition
244
245 # print only if "inevitable" is present in the given text
246 txt = "Death is inevitable can't show mercy."
247 if "inevitable" in txt:
248 print("Yes, 'inevitable' is present.")
249
250 ## Check if NOT

localhost:52376/178a6b89-515c-48d4-81b2-a951d8109a59/ 5/27
11/30/25, 8:30 PM new [Link]

251 # To check if a certain phrase or character is NOT present in a string, we can use the
keyword not in.
252 text="Long ago when light invaded my [Link] symbiotes betrayed me and imprisoned me."
253 if "hope" not in text:
254 print("condition is true, hope is not present")
255 else:
256 print("condition is false, hope is present")
257
258 # STRING SLICING
259 #Slicing, You can return a range of characters by using the slice [Link] the
start index and the end index, separated by a colon, to return a part of the string.
260 b="knull, void"
261 print(b[2:10:2]) # string[start:end:step]
262 print(len(b))
263 # 🥶 slicing with negative indexing
264 c="shutter island"
265 print(c[-10:-2:1]) # here when we use negative indexing, end par jo index likha hai
uss se ek pehle vaale tak slicing hogi like " -2 " likha hai to slicing " -3 " tak hogi
266
267 # MODIFY STRINGS
268 # Python has a set of built-in methods that you can use on strings.
269 # Note: All string methods returns new values. They do not change the original string.
270
271 # 1. capitalize() »»» returns a string where the first character is upper case,
and the rest is lower case.
272 txt = "python is FUN!"
273 x = [Link]()
274 print (x)
275
276 # 2. casefold() »»» This method is similar to the lower() method, but the
casefold() method is stronger, more aggressive, meaning that it will convert more
characters into lower case, and will find more matches when comparing two strings and
both are converted using the casefold() method.
277 b="Hello World!"
278 print([Link]())
279 c_german="Straße"
280 print(c_german.casefold())
281
282 # 3. lower() »»» This method performs a basic conversion of uppercase letters
to their lowercase equivalents. For most common English characters, it works as expected.
However, it retains certain special characters, like the German sharp s ('ß'), in their
original form if they are considered lowercase in their respective scripts.
283 d="Hello World!"
284 print([Link]())
285 e_german="Straße"
286 print(e_german.lower())
287
288 # 4. center() »»» The center() method will center align the string, using a
specified character (space is default) as the fill character.
289 txt = "banana"
290 x = [Link](20) # [Link](length, character) # default
character is space
291 print(x)
292

localhost:52376/178a6b89-515c-48d4-81b2-a951d8109a59/ 6/27
11/30/25, 8:30 PM new [Link]

293 # 5. encode() »»» The encode() method encodes the string, using the specified
encoding. If no encoding is specified, UTF-8 will be used.
294 # example
295 # → These examples uses ascii encoding, and a character that cannot be encoded, showing
the result with different errors:
296 txt="My name is Ståle"
297 print([Link](encoding="ascii",errors="backslashreplace"))
298 print([Link](encoding="ascii",errors="ignore"))
299 print([Link](encoding="ascii",errors="namereplace"))
300 print([Link](encoding="ascii",errors="replace"))
301 print([Link](encoding="ascii",errors="xmlcharrefreplace"))
302
303 # encoding refers to the process of converting a Unicode string (human-readable text)
into a sequence of bytes.
304 # errors parameter in the encode() method specifies how to handle characters that cannot
be encoded using the specified encoding scheme.
305 # 🤔🤔
306 # 'backslashreplace' - uses a backslash instead of the character that could not
be encoded
307 # 'ignore' - ignores the characters that cannot be encoded
308 # 'namereplace' - replaces the character with a text explaining the
character
309 # 'strict' - Default, raises an error on failure
310 # 'replace' - replaces the character with a questionmark
311 # 'xmlcharrefreplace' - replaces the character with an xml character
312
313 # 6. find() »»» The find() method find the first occurence of the specified
value. The find() method retturns -1 if the value is not found.
314 txt="You think darkness is your ally.I was born in it, molded by it. "
315 x = [Link]("e", 4, 16) # [Link](value, start, end)
316 print(x)
317
318 # If the value is not found, the find() method returns -1, but the index() method will
raise an exception:
319 txt = "Hello, welcome to my world."
320 print([Link]("q"))
321 # ▶▶ print([Link]("q")) # this will generate error
322
323 # 7. index() »»» The index() method finds the first occurrence of the
specified [Link] index() method raises an exception if the value is not found.
324 # [Link](value, start, end)
325
326 # 8. upper() »»» The upper() method returns a string where all characters
are in upper [Link] and numbers are ignored.
327 tx="vengeance is mine"
328 x=[Link]()
329 print(x)
330
331 # 9. count() »»» The count() method returns the number of times a specified
value appears in the string.
332 txt = "I love apples, apple are my favorite fruit"
333 x = [Link]("apple", 10, 24)
334 print(x)
335

localhost:52376/178a6b89-515c-48d4-81b2-a951d8109a59/ 7/27
11/30/25, 8:30 PM new [Link]

336 # 10. split() »»» The split() method splits a string into a [Link] can
specify the separator, default separator is any whitespace.
337 # Note: When maxsplit is specified, the list will contain the specified number of
elements plus one.
338 txt = "thor#loki#antman#deadpool#rogers#clint"
339 x = [Link]("#",2) # setting the maxsplit parameter to 1, will return a
list with 2 elements!
340 print(x)
341
342 # 11. isalnum() »»» The isalnum() method returns True if all the characters are
alphanumeric, meaning alphabet letter (a-z) and numbers (0-9).characters that are not
alphanumeric: (space)!#%&? etc.
343 txt = "Company12"
344 x = [Link]()
345 print(x)
346
347 # 12. isalpha() »»» The isalpha() method returns True if all the characters are
alphabet letters (a-z).characters that are not alphabet letters: (space)!#%&? etc.
348 txt = "CompanyX"
349 x = [Link]()
350 print(x)
351
352 # 13. isascii() »»» The isascii() method returns True if all the characters are
ascii characters (a-z).
353 txt = "Company123"
354 x = [Link]()
355 print(x)
356
357
358
359
360
361
362
363 # STRING CONCATENATION
364 # To concatenate, or combine, two strings you can use the + operator.
365 a = "Hello"
366 b = "World"
367 c = a + " " + b
368 print(c)
369
370 # PYTHON FORMAT STRINGS
371 # f-strings
372 age=1500
373 print(f"my name is Thor,I am {age} years old")
374 # A placeholder can contain variables, operations, functions, and modifiers to format the
value.
375 price = 59
376 txt = f"The price is {price} dollars"
377 print(txt)
378
379 # A placeholder can include a modifier to format the value.
380 # A modifier is included by adding a colon : followed by a legal formatting type, like
.2f which means fixed point number with 2 decimals:
381 price = 59
localhost:52376/178a6b89-515c-48d4-81b2-a951d8109a59/ 8/27
11/30/25, 8:30 PM new [Link]

382 txt = f"The price is {price:.2f} dollars"


383 print(txt)
384 # A placeholder can contain Python code, like math operations:
385
386 # ESCAPE CHARACTERS
387 #To insert characters that are illegal in a string, use an escape [Link] escape
character is a backslash \ followed by the character you want to [Link] example of an
illegal character is a double quote inside a string that is surrounded by double quotes:
388 #
389 # ⩺⩺ You will get an error if you use double quotes inside a string that is surrounded
by double quotes:
390 # txt = "We are the so-called "Vikings" from the north." # 😎 To fix this problem,
use the escape character \":
391
392 txt = "We are the so-called \"Vikings\" from the north."
393 print(txt)
394
395 # other escape characters:
396 # \' single quote
397 # \" double quote
398 # \n new line
399 # \r carriage return
400 # \t tab
401 # \b backspace
402 # \f form feed
403 # \ooo octal value
404 # \xhh hex value
405 # \\ backslash
406
407
408 # ❄️❄️ PYTHON LIST
409 # A list is a collection which is ordered and changeable In Python allows duplicate
[Link] are written with square [Link] are one of 4 built-in data types in
Python used to store collections of data, the other 3 are Tuple, Set, and Dictionary, all
with different qualities and usage.
410 # Lists are used to store multiple items in a single variable.
411
412 lst=["ironman","captian america","thor","hulk"]
413 print(lst)
414 # Ordered - when we say that lists are ordered, it means that the items have a defined
order, and that order will not [Link] we add new items to the list, the new items will
be placed at the end of the list.
415 # changeable - lists are changeable, meaning that we can change, add, remove items in a
list after it has been created.
416 # Allow duplicates - since lists are indexed lists can have items with the same value.
417 thislist = ["apple", "banana", "cherry", "apple", "cherry"]
418 print(thislist) # ✨ The simple reason that lists allow duplicates is
because a list's purpose is to record items in a specific order, not to track uniqueness.
419 #
420 # List length
421 print(len(lst)) # ['ironman', 'captian america', 'thor', 'hulk']
422 # List Items - Data Types ⩥⩥ list items can be of any data type;
423 list1=["apple","banana","cherry"] # string
424 list2=[1,8,9,6,4] # integer
425 list3=[True,False,True] # boolean

localhost:52376/178a6b89-515c-48d4-81b2-a951d8109a59/ 9/27
11/30/25, 8:30 PM new [Link]

426 # list can also contain different data types at the same time.
427 list4=["abc",34,True,4.5]
428 print(list4)
429 #
430 # the list() construstor
431 # It is also possible to use the list() constructor when creating a new list.
432 newlist=list(("ironman","thor","loki","steven strange")) # here we use the
double round brackets
433 print(newlist)
434 # ACCESS LIST ITEMS
435 # list items are indexed and we can access them by reffering to the index number.
436 print(newlist[1]) # output will be thor
437 # Negative indexing
438 print(newlist[-2]) # output will be loki
439
440 # list slicing
441 lxt=["thomas shelby","arthur shelby","ada shelby","johnny dog","jerimaiah","alfie
solomons"]
442 print(lxt[1:5:2]) # the item at index 5 will not be included in the output
443 # with negative indexing
444 print(lxt[-1:-5:2]) # output will be an empty list because when we use negative
indexing the slicing goes from right to left so -1 is greater than -5.
445 print(lxt[-5:-1:2]) # end index item will not be included in the output.
446
447 # check if item exists
448 lxt=["thomas shelby","arthur shelby","ada shelby","johnny dog","jerimaiah","alfie
solomons"]
449 if "ada shelby" in lxt:
450 print("yes, ada shelby is present in the list")
451 # CHANGE LIST ITEMS
452 lxt=["thomas shelby","arthur shelby","ada shelby","johnny dog","jerimaiah","alfie
solomons"]
453 lxt[3]="aberama gold"
454 print(lxt)
455 # change of range of items
456 lxt=["thomas shelby","arthur shelby","ada shelby","johnny dog","jerimaiah","alfie
solomons"]
457 lxt[1:3]=["polly gray","micheal gray"] # changing the values at index 1 and 2
458 print(lxt)
459 # Note: The length of the list will change when the number of items inserted does not
match the number of items replaced.
460 thislist = ["apple", "banana", "cherry"]
461 thislist[1:3] = ["watermelon"]
462 print(thislist)
463 #
464 # insert items
465 # To insert a new list item, without replacing any of the existing values, we can use the
insert() [Link] method inserts an item at the specified value.
466 thislist = ["apple", "banana", "cherry"]
467 [Link](2, "watermelon")
468 print(thislist)
469
470 # ADD LIST ITEMS
471
472 # 1. Append items # to add an item to the end of the list, use append()
localhost:52376/178a6b89-515c-48d4-81b2-a951d8109a59/ 10/27
11/30/25, 8:30 PM new [Link]

473 thislist = ["apple", "banana", "cherry"]


474 [Link]("orange")
475 print(thislist)
476
477 # 2. Insert items # to insert the item at a specified index, use insert()
478 newlist=["christane","ben","robert"]
479 [Link](1,"keaton") # this will inset the " keaton " at 1 index
480 print(newlist)
481
482 # 3 Extend list # to add the items of the another list to the current list,use
extend()
483 [Link](newlist) # we used here the above two lists
484 print(thislist)
485
486 # 4 Add any iterable # you can add any iterable (tuples, sets, dictionaries etc.) to a
list using the extend() method.
487 thislist = ["apple", "banana", "cherry"]
488 thistuple = ("kiwi", "orange")
489 [Link](thistuple) # here we are adding a tuple to the list
490 print(thislist)
491
492 # REMOVE LIST ITEMS
493
494 # 1. remove() »»» The remove() method removes the specified item.
495 listh=["ironman","captian america","thor","hulk"]
496 [Link]("thor")
497 print(listh)
498
499 # 2. pop() »»» The pop() method removes the item at specified index, (or the last
item if index is not specified).
500 listh=["ironman","captian america","thor","hulk"]
501 [Link](1) # here we are removing the item at index 1
502 print(listh)
503
504 # 3. del keyword »»» The del keyword also removes the specified index.
505 listh=["ironman","captian america","thor","hulk"]
506 del listh[0] # here we are deleting the item at index 0
507 print(listh)
508 # 🌟 del keyword can also delete the list completely
509
510 # 4. clear() »»» The clear() method empties the whole list.
511 lsth=["india","russia","china","brazil","south africa"]
512 [Link]()
513 print(lsth)
514
515 # LOOP LISTS
516
517 # loop through a list
518 lead=["modi","putin","benjamin","yogi","hemant"]
519 for i in lead:
520 print(i) # use when you care only about the values.
521
522 # loop through the index numbers
523 fruits = ["apple", "banana", "cherry"]

localhost:52376/178a6b89-515c-48d4-81b2-a951d8109a59/ 11/27
11/30/25, 8:30 PM new [Link]

524 for i in range(len(fruits)): # here we are looping through the index numbers (0,
1, 2) and using them to access items.
525 print(i, fruits[i]) # use When you need positions (e.g. modifying or
comparing by index)
526 # exaple with enumerate()
527 # with the enumerate() function we can loop thorugh a list and have an automatic counter.
528 fruits = ["apple", "banana", "cherry"]
529 for i, fruit in enumerate(fruits):
530 print(i, fruit) # use when you want both the index and the value cleanly.
531
532 # Using a while loop
533 # use the len() function to determine the length of the list, then start at 0 and
remember to increase the index by 1 after each iteration.
534 cars=["ford","tata","volvo","toyota"]
535 i=0
536 while i < len(cars):
537 print(cars[i])
538 i += 1
539
540 # LIST COMPREHENSION
541 # looping using list comprehension
542 # list comprehension offers the shortest syntax for looping through lists.
543 cars2=["mazerati","hyundai","nissan","tesla"]
544 [print(x) for x in cars2]
545 # List comprehension offers a shorter syntax when you want to create a new list based on
the values of an existing list.
546
547 # without list comprehension you will have to write a for statement with a conditional
test inside the loop, and the append() method to add values to a new list.
548 fruits = ["apple", "banana", "cherry", "kiwi", "mango"]
549 newlist = []
550 for x in fruits:
551 if "a" in x:
552 [Link](x)
553 print(newlist)
554
555 # with list comprehension you can do all that with only one line of code
556 fruits = ["apple", "banana", "cherry", "kiwi", "mango"]
557 newlist = [x for x in fruits if "a" in x]
558 print(newlist)
559
560 # SORT LIST
561
562 # 1. sort list alphanumerically
563 # sort() method will sort the list alphanumerically, ascending by default.
564 thislist=["orange","mango","kiwi","pineapple","banana"] # sorting the list
alphabetically
565 [Link]()
566 print(thislist)
567
568 tslist = [100, 50, 65, 82, 23] # sorting the list numerically
569 [Link]()
570 print(tslist)
571

localhost:52376/178a6b89-515c-48d4-81b2-a951d8109a59/ 12/27
11/30/25, 8:30 PM new [Link]

572 # 2. sort descending


573 thislist = ["orange", "mango", "kiwi", "pineapple", "banana"]
574 [Link](reverse=True)
575 print(thislist)
576
577 nlist=[100,89,55,75,20,150]
578 [Link](reverse=True)
579 print(nlist)
580
581 # 3. customize sort function
582 def myfunc(n):
583 return abs(n - 50) # abs() → this is a built-in function that gives the
absolute value of a number.
584 thislist = [100, 50, 65, 82, 23]
585 [Link](key = myfunc) # " key = myfunc " → This tells Python to use the
function myfunc to decide the sorting order.
586 print(thislist)
587 # so overall this code is used to tell how close each number is to 50 by sorting them
588
589 # 4. Case Insensitive Sort
590
591 # By default the sort() method is case sensitive, resulting in all capital letters being
sorted before lower case letters.
592 thislist = ["banana", "Orange", "Kiwi", "cherry","Apple","Pineapple"]
593 [Link]()
594 print(thislist)
595
596 # so if you want the case insensitive sort, use [Link] as key function
597 thislist = ["banana", "Orange", "Kiwi", "cherry","Apple","Pineapple"]
598 [Link](key = [Link])
599 print(thislist)
600
601 # 5. reverse the list
602 # reverse() method reverses the whole list like the first item will become last and the
last item will become first.
603 thislist = ["banana", "Orange", "Kiwi", "cherry","Apple","Pineapple"]
604 [Link]()
605 print(thislist)
606
607 # COPY LISTS
608 # you cannot simply copy list by typing list1=list2, because list2 will only be a
refernece to list1, and changes made in list1 will automatically also made in list2.
609
610 # using the copy() method
611 thislist = ["apple", "banana", "cherry"]
612 mylist = [Link]()
613 print(mylist)
614
615 # using the list() method
616 lista=["strange","tyler","patrick","denial"]
617 listb=list(lista)
618 print(listb)
619
620 # using the slice operator

localhost:52376/178a6b89-515c-48d4-81b2-a951d8109a59/ 13/27
11/30/25, 8:30 PM new [Link]

621 listc=["deathstroke","joker","penguin","ivy poison"]


622 listd=listc[:] # making a copy of the list with the : operator
623 print(listd)
624
625 # JOINING LISTS
626 # there are several ways of joining two or more lists, but the simplest method is by
using + operator
627 list1 = ["a", "b", "c"]
628 list2 = [1, 2, 3]
629 list3 = list1 + list2
630 print(list3)
631 # another way to join two list by appending all the elements of list2 into list1, one by
one.
632 # appenidng list2 into list1
633 list1=["d","e","f","g","h"]
634 list2=[3,5,8,9]
635 for i in list2:
636 [Link](i)
637 print(list1)
638
639 # we can also use the extend() method
640 list1=["d","e","f","g","h"]
641 list2=[3,5,8,9]
642 [Link](list2)
643 print(list1)
644
645
646 # TUPLES
647 # typles are also used to store multiple items in a single [Link] is a collection
which is ordered and unchangeable and also allows duplicate values.
648 thistuple = ("apple", "banana", "cherry")
649 print(thistuple)
650 # allow duplicates ⁓ since tuples are indexed they can have items with same values.
651 tstuple=("apple","banana","kiwi","cherry","apple","kiwi")
652 print(tstuple)
653
654 # creating tuple with one item
655 thistuple = ("apple",)
656 print(type(thistuple))
657 #NOT a tuple
658 thistuple = ("apple")
659 print(type(thistuple))
660 # a tuple can contain different data types.
661
662 # tuple() constructor
663 thistuple = tuple(("apple", "banana", "cherry")) # note the double round-brackets
664 print(thistuple)
665
666 # ACCESS TUPLES
667 thistuple = ("apple", "banana", "cherry","kiwi","waterrmelon")
668 print(thistuple[1])
669 # accesing tuple item with negative indexing
670 thistuple = ("apple", "banana", "cherry","kiwi","waterrmelon")
671 print(thistuple[-2])

localhost:52376/178a6b89-515c-48d4-81b2-a951d8109a59/ 14/27
11/30/25, 8:30 PM new [Link]

672
673 # SLICING TUPLES
674
675 ftuple=("apple","banana","cherry","kiwi","pineapple","melon","mango")
676 print(ftuple[2:5]) # the value at index 5 will not be displayed
677 # syntax -- tuple[start:end:step] ✨ the value at " end " index will not be
displayed uss se ek pehle vaali tak hi display hoga.
678
679 thistuple = ("apple", "banana", "cherry", "orange", "kiwi", "melon", "mango")
680 print(thistuple[:4]) # This example returns the items from the beginning to, but NOT
included, "kiwi"
681
682 thistuple = ("apple", "banana", "cherry", "orange", "kiwi", "melon", "mango")
683 print(thistuple[-4:-1]) # This example returns the items from index -4 (included)
to index -1 (excluded)
684
685 # getting the tuple in reverse order
686 thistuple = ("apple", "banana", "cherry", "orange", "kiwi", "melon", "mango")
687 print(thistuple[::-1])
688
689 # check if item exists
690 frtuple=("apple","banana","mango")
691 if "apple" in frtuple:
692 print("yes, apple is present in fruit tuple")
693 else:
694 print("apple not found")
695
696 # UPDATE TUPLES
697 # change tuple values -- tuple is immutable and unchangeable we cannnot change the tuple
directly but we can make the tuple first into list and then change that list and then
convert it back into tuple.
698 x=("apple","banana","cherry")
699 y=list(x) # converting the tuple into list
700 y[1]="kiwi" # changing the item value
701 x=tuple(y) # converting the list back into the tuple
702 print(x)
703
704 # ADD ITEMS there are two methods for adding items to tuple
705 # 1. convert into list
706 thistuple = ("apple", "banana", "cherry")
707 y = list(thistuple)
708 [Link]("orange")
709 thistuple = tuple(y)
710
711 # 2. add tuple to tuple
712 thistuple = ("apple", "banana", "cherry")
713 y = ("orange",) # 🤐 when creating tuple with only one item remember to include
a comma after the item, otherwise it will not be identified as string.
714 thistuple += y
715 print(thistuple)
716
717 # REMOVE ITEMS
718
719 thistuple = ("apple", "banana", "cherry")

localhost:52376/178a6b89-515c-48d4-81b2-a951d8109a59/ 15/27
11/30/25, 8:30 PM new [Link]

720 y = list(thistuple)
721 [Link]("apple")
722 thistuple = tuple(y)
723 print(thistuple)
724
725 # deleting the tuple completely
726 xtuple=("henry","ben","clark")
727 del xtuple
728 # by printing xtuple will raise an error because this no longer exists
729
730 # UNPACK TUPLES
731 # unpacking a tuple -- When we create a tuple, we normally assign values to it. This is
called "packing" a [Link] in python, we are also allowed to extract the values back
into the variables. this is called "unpacking".
732 fruits = ("apple", "banana", "cherry")
733 (x,y,z) = fruits
734 print(x)
735 print(y)
736 print(z)
737 # the number of variables must match the number of values in the tuple, if not we must
use an asterisk* to collect the remaining values as list
738
739 # using Asterisk(*)
740 # If the number of variables is less than the number of values, you can add an * to the
variable name and the values will be assigned to the variable as a list:
741 fruits = ("apple", "banana", "cherry", "strawberry", "raspberry")
742 (green, yellow, *red) = fruits
743 print(green)
744 print(yellow)
745 print(red)
746
747 # If the asterisk is added to another variable name than the last, Python will assign
values to the variable until the number of values left matches the number of variables
left.
748 fruits = ("apple", "mango", "papaya", "pineapple", "cherry","banana")
749 (green, *tropic, red) = fruits
750 print(green)
751 print(tropic)
752 print(red)
753
754 # LOOP TUPLES
755
756 # loop through a tuple
757 thistuple = ("apple", "banana", "cherry")
758 for x in thistuple:
759 print(x)
760
761 # loop through the index numbers -- loop through the items by referring to their index
numbers. use range() and len() function
762 thistuple = ("grape", "mango", "melon")
763 for i in range(len(thistuple)):
764 print(thistuple[i])
765
766 # using a while loop

localhost:52376/178a6b89-515c-48d4-81b2-a951d8109a59/ 16/27
11/30/25, 8:30 PM new [Link]

767 # Use the len() function to determine the length of the tuple, then start at 0 and loop
your way through the tuple items by referring to their [Link] to increase the
index by 1 after each iteration.
768 thistuple = ("green lantern", "hawkgirl", "mr terrific")
769 i = 0
770 while i < len(thistuple):
771 print(thistuple[i])
772 i = i + 1
773
774 # JOIN TUPLES
775
776 # join two or more tuples -- to join two or more tuples you can use + operator
777 tuple1 = ("a", "b" , "c")
778 tuple2 = (1, 2, 3)
779 tuple3 = tuple1 + tuple2
780 print(tuple3)
781
782 # multiply tuples -- if we want to multiply the content of a tuple to a given number
of times, use * operator
783 fruits = ("apple", "banana", "cherry")
784 mytuple = fruits * 2
785 print(mytuple)
786
787 # TUPLE METHODS -- we can use two built-in methods count() and index() on tuple
788
789 # count()
790 numtuple=(1,5,2,3,9,7,5,6,5,10,11)
791 x=[Link](5)
792 print(x)
793
794 # index() -- search for the first occurence of that specified value and return it's
position.
795 thistuple = (1,5,2,3,9,10,5,7,6,9)
796 x = [Link](9)
797 print(x)
798
799 # PYTHON SETS
800 # sets are also used to store multiple values in a single variable. a set is a collection
which is unordered, unchangeable and unindexed.
801 # sets are unchangeable, but you can add new items and remove [Link] are written with
curly brackets {} .
802 thisset = {"apple", "banana", "cherry"}
803 print(thisset) # sets are unordered so we cannot be sure in which order the
items will appear.
804 # sets are unordered, unchangeable, unindexed and do not allow duplicate values
805
806 # duplicates not allowed -- duplicate values will be ignored
807 thisset = {"apple", "banana", "cherry", "apple"}
808 print(thisset)
809
810 # the value ( True and 1 ),( False and 0 ) are considered the same in sets and are
treated as duplicates.
811 thisset = {"apple", "banana", "cherry", True, 1, 2}
812 print(thisset)
813
localhost:52376/178a6b89-515c-48d4-81b2-a951d8109a59/ 17/27
11/30/25, 8:30 PM new [Link]

814 # get the length of a set -- use the len() function to get the length of the set
815
816 # set items- data types
817 # set items can be of any type ⩥⩥ string,int,boolean and float
818 set1 = {"apple", "banana", "cherry"}
819 set2 = {1, 5, 7, 9, 3}
820 set3 = {True, False, False}
821 print(set1)
822 print(set2)
823 print(set3)
824 # a set can contain different types in that particular set also
825 myset = {"apple", "banana", "cherry"}
826 print(type(myset))
827
828 # The set() constructor
829 thisset = set(("apple", "banana", "cherry")) # note the double round-brackets
830 print(thisset)
831
832 # ACCESS SET ITEMS
833 # access items -- you cannot access items in a set by referring to an index or a
[Link] you can loop through the set by using " for " loop or ask if a specified value is
present in the set or not by using " in " keyword
834 thisset = {"apple", "banana", "cherry"}
835 for x in thisset:
836 print(x)
837 # check if "banana" is present in set
838 thisset = {"apple", "banana", "cherry"}
839 print("banana" in thisset) # this will give output = True
840 # check if "banana" is NOT present in set
841 thisset = {"apple", "banana", "cherry"}
842 print("banana" not in thisset) # this will give output = False
843
844 # change items # ❄️❄️ once set is created you cannot change the items in it but
you can add new items
845
846 # ADD SET ITEMS
847
848 # 1. add items
849 thisset = {"apple", "banana", "cherry"}
850 [Link]("orange")
851 print(thisset)
852
853 # 2. add sets
854 thisset = {"apple", "banana", "cherry"}
855 tropical = {"pineapple", "mango", "papaya"}
856 [Link](tropical)
857 print(thisset)
858
859 # 3. add any iterable
860 thisset = {"apple", "banana", "cherry"}
861 mylist = ["kiwi", "orange"]
862 [Link](mylist)
863 print(thisset)
864

localhost:52376/178a6b89-515c-48d4-81b2-a951d8109a59/ 18/27
11/30/25, 8:30 PM new [Link]

865 # REMOVE SET ITEMS


866
867 # 1. remove() ▶▶ if the item to remove does not exist then remove() method will
raise an error.
868 thisset = {"apple", "banana", "cherry"}
869 [Link]("banana")
870 print(thisset)
871
872 # 2. discard() ▶▶ if the item to remove does not exist then discard() will NOT raise
an error.
873 thisset = {"apple", "banana", "cherry"}
874 [Link]("banana")
875 print(thisset)
876
877 # 3. pop() method ▶▶ this method will remove a random item so we cannot be sure what
item will be removed, the return value of the pop() method is the removed item.
878 thisset = {"apple", "banana", "cherry"}
879 x = [Link]()
880 print(x)
881 print(thisset)
882 # sets are unordered so when using the pop() method we will not know which item will be
removed.
883
884 # 4. clear() ▶▶ the clear() method empties the set.
885 thisset = {"apple", "banana", "cherry"}
886 [Link]()
887 print(thisset)
888
889 # using del() keyword ▶» the del() method will delete the set completely and will
raise an error when we trie to print that set because that no longer exists.
890 thisset = {"apple", "banana", "cherry"}
891 del thisset
892
893 # LOOP SETS
894 # we can loop through the set by using for loop
895 thisset = {"apple", "banana", "cherry"}
896 for x in thisset:
897 print(x)
898
899 # JOIN SETS 🦇🦇🦇🦇🦇🦇
900 # there are several ways to join two or more sets
901 # union()
902 # update()
903 # intersection()
904 # difference()
905 # symmetric difference()
906
907 # 1. union() ⇒ union() method returns a new set with all items from both sets.
908 set1 = {"a", "b", "c"}
909 set2 = {1, 2, 3}
910 set3 = [Link](set2) # we can also use | operator for union of sets.
911 print(set3)
912
913 # join multiple sets

localhost:52376/178a6b89-515c-48d4-81b2-a951d8109a59/ 19/27
11/30/25, 8:30 PM new [Link]

914 set1 = {"a", "b", "c"}


915 set2 = {1, 2, 3}
916 set3 = {"John", "Elena"}
917 set4 = {"apple", "bananas", "cherry"}
918 myset = [Link](set2, set3, set4)
919 print(myset)
920 # by using | operator
921 set1 = {"a", "b", "c"}
922 set2 = {1, 2, 3}
923 set3 = {"arthur", "thomas"}
924 set4 = {"apple", "bananas", "cherry"}
925 myset = set1 | set2 | set3 |set4
926 print(myset)
927
928 # join a set and a tuple
929 # the union method allows you to join a set with other datatypes like lists and tuples.
930 x = {"a","b","c"}
931 y = (1,2,3,45)
932 z = [Link](y)
933 print(z)
934 # 🤔 the | operator allows you to join set with set not like the union() like in that
method you can join a set with list or tuple.
935
936 # 2. update() ⇒ the update() method inserts all the items from one set to another set.
the update() changes the original set and does not return a new set.
937 set1 ={"a","b","c"}
938 set2 = (1,2,3)
939 [Link](set2)
940 print(set1)
941 # 🤔 both union() and update() will exclude any duplicate values.
942
943 # 3. intersection() ⇒ the instersection() method will return a new set that contains the
items which are present in both the sets i.e. the common items.
944 set1 = {"apple", "banana", "cherry"}
945 set2 = {"google", "microsoft", "apple"}
946 set3 = [Link](set2) # we can use the & operator instead of intersection()
to get the same result.
947 print(set3)
948 # using & operator
949 set4 ={"batman","superman","shazam"}
950 set5 ={"ironman","captian america","moonknight","batman"}
951 set6 =set4 & set5
952 print(set6)
953 # 🤔 the & operator allows you to join sets with the sets not with the other datatypes
like the intersection() like sets with list and tuple.
954 # ⩥⩥ intersection_update() method
955 # note: -- the intersection_update() method will also keep only the duplicates, but also
it will change the original set instead of returining a new [Link] don't have to store
the value to a new set here.
956 set1 = {"apple", "banana", "cherry"}
957 set2 = {"google", "microsoft", "apple"}
958 set1.intersection_update(set2)
959 print(set1)
960

localhost:52376/178a6b89-515c-48d4-81b2-a951d8109a59/ 20/27
11/30/25, 8:30 PM new [Link]

961 # 4. differrence() ⇒ this difference() method will reurn a new set that will contain
only the items from the first set that are not present in the other set.
962 set1 = {"apple", "banana", "cherry"}
963 set2 = {"google", "microsoft", "apple"}
964 set3 = [Link](set2)
965 print(set3)
966
967 # ⩥⩥ difference_update() -- this method will also keep the items from the first set that
are not in the other set, but it will change the original set instead of returning a new
set.
968 set1 = {"apple", "banana", "cherry"}
969 set2 = {"google", "microsoft", "apple"}
970 set1.difference_update(set2)
971 print(set1)
972
973 # 5. symmetric_differnece­
() ⇒ this method will keep only the items that are NOT present
in both the sets.
974 set1 = {"apple", "banana", "cherry"}
975 set2 = {"google", "microsoft", "apple"}
976 set3 = set1.symmetric_difference­
(set2) # we can use ' ^ ' operator instead of
symmetric_difference­
() but here is a constraint that this operator action is only valid
for joining sets with sets.
977 print(set3)
978
979 # ⩥⩥ symmetric_differnce_­update() -- this method will also keep all the duplicates, but
it will change the original set instead of returning a new set.
980 set1 = {"apple", "banana", "cherry"}
981 set2 = {"google", "microsoft", "apple"}
982 set1.symmetric_difference­
_update(set2)
983 print(set1)
984
985 # FROZEN SETS -- A frozenset in Python is an immutable version of a standard set. Like a
regular set, it is an unordered collection of unique elements. However, once a frozenset
is created, its elements cannot be added, removed, or modified
986 my_list = [1, 2, 3, 2, 4]
987 my_frozenset = frozenset(my_list)
988 print(my_frozenset)
989
990 x = frozenset({"apple", "banana", "cherry"})
991 print(x)
992 print(type(x))
993
994 # frozenet methods
995 # Being immutable means you cannot add or remove elements. However, frozensets support
all non-mutating operations of sets.
996 # Frozenset: Can only be created using the constructor frozenset([1, 2]). There is no
shortcut syntax like {} for frozensets.
997 # Frozenset: Immutable. Once created, it is set in stone. Attempting to modify it will
crash your program.
998
999 # 1. copy() ⇿ retunrs a shallow copy
1000 fs = frozenset({1, 2, 3})
1001 cp = [Link]()
1002 print(fs)
1003 print(cp)

localhost:52376/178a6b89-515c-48d4-81b2-a951d8109a59/ 21/27
11/30/25, 8:30 PM new [Link]

1004
1005 # 2. difference() ⇿ retunrs a new frozen set with the difference of two or more frozen
sets.
1006 a = frozenset({1, 2, 3, 4})
1007 b = frozenset({3, 4, 5})
1008 print([Link](b))
1009 print(a - b)
1010
1011 # 3. intersection() ⇿ returns a new frozen set with the intersection of two or more
frozen sets.
1012 a = frozenset({1, 2, 3, 4})
1013 b = frozenset({3, 4, 5})
1014 print([Link](b))
1015 print(a & b)
1016
1017 # 4. isadjoint() ⇿ returns True if two frozen sets have no elements in common.
1018 a = frozenset({1, 2})
1019 b = frozenset({3, 4})
1020 c = frozenset({2, 3})
1021 print([Link](b))
1022 print([Link](c))
1023
1024 # 5. issubset() ⇿ returns True if this subset is proper subset of another set.
1025 a = frozenset({1, 2})
1026 b = frozenset({1, 2, 3})
1027 print([Link](b))
1028 print(a <= b)
1029 print(a < b)
1030
1031 # 6. issuperset() ⇿ returns True if this set is a proper suoerset of another set.
1032 a = frozenset({1, 2, 3})
1033 b = frozenset({1, 2})
1034 print([Link](b))
1035 print(a >= b)
1036 print(a > b)
1037
1038 # 7. symmetric_difference­
() ⇿ returns a new frozen set with the symmetric difference of
two frozen sets.
1039 a = frozenset({1, 2, 3})
1040 b = frozenset({3, 4, 5})
1041 print(a.symmetric_difference­
(b))
1042 print(a ^ b)
1043
1044 # 8. union() ⇿ returns a new frozen set containing the union of two or more sets.
1045 a = frozenset({1, 2})
1046 b = frozenset({2, 3})
1047 print([Link](b))
1048 print(a | b)
1049
1050 # To be clear, frozenset does not support any method that would change the object in-
place.
1051 # ❌ .add()
1052 # ❌ .remove()
1053 # ❌ .discard()

localhost:52376/178a6b89-515c-48d4-81b2-a951d8109a59/ 22/27
11/30/25, 8:30 PM new [Link]

1054 # ❌ .pop()
1055 # ❌ .clear()
1056 # ❌.update() (and intersection_update, etc.)
1057 # One Extra Feature: frozenset supports one non-mutating operation that set does not:
1058
1059
1060 # PYTHON DICTIONARIES
1061 # A dictionary is a collection which is ordered*, changeable and do not allow duplicates.
In Python dictionaries are written with curly brackets, and they have keys and values.
1062 thisdict = {
1063 "brand": "Ford",
1064 "model": "Mustang",
1065 "year": 1964
1066 }
1067 print(thisdict)
1068 # dictionaries are changeable means we can add, remove or change irems after the
dictionary has been created.
1069 # dicionaries do not allow duplicates -- duplicate keys are not allowed, but values can
be duplicated.
1070 thisdict = {
1071 "brand": "Ford",
1072 "model": "Mustang",
1073 "year": 1964,
1074 "year": 2020
1075 }
1076 print(len(thisdict))
1077 # since dicionaries are ordered, the items have a defines order, and that order will not
change.
1078
1079
1080 # Dicinoary items - data types == dictionary items can be of any data type:
1081 dict2={"brand":"Ford","model":"Mustang","year":1984}
1082 dict3={1:"apple",2:"banana",3:"cherry"}
1083 dict4={True:"yes",False:"no"}
1084 print(dict2)
1085 print(dict3)
1086 print(dict4) # a dicionary can contain different data types as key and value also.
1087
1088 # the dict() constructor
1089 thisdict = dict(name="john",age=30,city="delhi")
1090 print(thisdict)
1091
1092
1093 # ACCESSING THE DICTIOANARY ITEMS
1094
1095 # getting the value of the "model" key the value of the specified key can be reffered by
using square brackets [] or the get() method.
1096 thisdict={"brand":"ford","model":"mustang","year":2013}
1097 x=thisdict["model"]
1098 print(x)
1099 y=[Link]("model")
1100 print(y)
1101
1102 # getting all the key

localhost:52376/178a6b89-515c-48d4-81b2-a951d8109a59/ 23/27
11/30/25, 8:30 PM new [Link]

1103 z=[Link]()
1104 print(z)
1105 # any change made to the dicionary will be reflected in the keys object as well.
1106 car = {
1107 "brand": "Ford",
1108 "model": "Mustang",
1109 "year": 1964
1110 }
1111 x = [Link]() # before doing any change
1112 print(x)
1113 car["color"]="white" # adding an item to the dictionary
1114 print(x)
1115
1116 # getting the values
1117 y=[Link]()
1118 print(y)
1119 car = {
1120 "brand": "Ford",
1121 "model": "Mustang",
1122 "year": 1964
1123 }
1124 print([Link]()) # before doing any change
1125 car["year"]=2028
1126 print([Link]()) # after the change
1127
1128 # getting all the items -- the both keys and values aswell
1129 capitals={"Germany": "Berlin", "Canada": "Ottawa", "England": "London"}
1130 print([Link]())
1131
1132 # check if key exists
1133 thisdict = {
1134 "brand": "Ford",
1135 "model": "Mustang",
1136 "year": 1964
1137 }
1138 if "model" in thisdict:
1139 print("Yes, 'model' is one of the keys in the thisdict dictionary")
1140
1141 # CHANGE DICIONARY ITEMS
1142 thisdict = {
1143 "brand": "Ford",
1144 "model": "Mustang",
1145 "year": 1964
1146 }
1147 thisdict["year"] = 2018 # changing the value of year
1148
1149 # update() method
1150 thisdict={"brand":'ford',"model":"ferrari","year":2089,"color":"red"}
1151 [Link]({"year":2049})
1152 print(thisdict)
1153
1154 # ADD DICIONARY ITEMS
1155

localhost:52376/178a6b89-515c-48d4-81b2-a951d8109a59/ 24/27
11/30/25, 8:30 PM new [Link]

1156 # Adding an item to the dictionary is done by using a new index key and assigning a value
to it:
1157 thisdict = {
1158 "brand": "Ford",
1159 "model": "Mustang",
1160 "year": 1964
1161 }
1162 thisdict["color"] = "red"
1163 print(thisdict)
1164
1165 # update() method
1166 thisdict={"brand":"ford","model":"toyota","year":2020}
1167 [Link]({"color":"black"})
1168 print(thisdict)
1169
1170
1171 # REMOVE DICTIONARY ITEMS
1172 # 1. pop() method -- removes the item with the specified key name, means you give key
name then the key value pair will be removed.
1173 tidict={"actor":"Al pacino","character":"micheal corleone","movie":"the godfather"}
1174 [Link]("character")
1175 print(tidict)
1176
1177 # 2. popitem() method -- removes the last inserted key-value pair, means item which was
added last will be removed.
1178 tidict={"actor":"Al pacino","character":"micheal corleone","movie":"the godfather"}
1179 [Link]() # this will remove "movie":"the godfather" key-value pair
1180 print(tidict)
1181
1182 # 3. del keyword -- removes the item with the specified key name.
1183 tidict={"actor":"Al pacino","character":"micheal corleone","movie":"the godfather"}
1184 del tidict["actor"]
1185 print(tidict)
1186 # the del keyword can also delete the whole dictionary
1187 thisdict = {
1188 "brand": "Ford",
1189 "model": "Mustang",
1190 "year": 1964
1191 }
1192 del thisdict
1193 # print(thisdict) here it will raise en error because the dictionary thisdict no
longer exists.
1194
1195 # 4. clear() method -- empties the dictionary
1196 thisdict = {
1197 "brand": "Ford",
1198 "model": "Mustang",
1199 "year": 1964
1200 }
1201 [Link]()
1202 print(thisdict)
1203
1204
1205 # LOOP DICTIONARY

localhost:52376/178a6b89-515c-48d4-81b2-a951d8109a59/ 25/27
11/30/25, 8:30 PM new [Link]

1206 # loop through a dictionary -- loop through dictionary items using for loop
1207
1208 # loop through dictionary to get all keys
1209 tidict={"actor":"Al pacino","character":"micheal corleone","movie":"the godfather"}
1210 for x in tidict: # this will give us all the keys
1211 print(x)
1212
1213 tidict={"actor":"Al pacino","character":"micheal corleone","movie":"the godfather"}
1214 for y in [Link]():
1215 print(y)
1216
1217 # loop through dictionary to get all the values
1218 tidict={"actor":"Al pacino","character":"micheal corleone","movie":"the godfather"}
1219 for z in tidict: # this will give us all the values of the dictionary one by
one
1220 print(tidict[z])
1221
1222 tidict={"actor":"Al pacino","character":"micheal corleone","movie":"the godfather"}
1223 for w in [Link]():
1224 print(w)
1225
1226 # loop to get the key-value pair
1227 country_capitals = {"Germany": "Berlin", "Canada": "Ottawa", "England": "London"}
1228 for k in country_capitals.items():
1229 print(k)
1230
1231 thisdict = {
1232 "brand": "Ford",
1233 "model": "Mustang",
1234 "year": 1964
1235 }
1236 for x, y in [Link]():
1237 print(x, y)
1238
1239
1240 # COPY DICTIONARY -- You cannot copy a dictionary simply by typing dict2 = dict1,
because: dict2 will only be a reference to dict1, and changes made in dict1 will
automatically also be made in dict2.
1241 # using the copy() method
1242 thisdict = {
1243 "brand": "Ford",
1244 "model": "Mustang",
1245 "year": 1964
1246 }
1247 mydict = [Link]()
1248 print(mydict)
1249
1250 # using the built-in function dic()
1251 thisdict = {
1252 "brand": "Ford",
1253 "model": "Mustang",
1254 "year": 1964
1255 }
1256 mydict = dict(thisdict)

localhost:52376/178a6b89-515c-48d4-81b2-a951d8109a59/ 26/27
11/30/25, 8:30 PM new [Link]

1257 print(mydict)
1258
1259
1260 # NESTED DICTIONARIES -- a dictionary conatainning multiple dictionary in itself.
1261
1262 myfamily = {
1263 "child1" : {
1264 "name" : "Emil",
1265 "year" : 2004
1266 },
1267 "child2" : {
1268 "name" : "Tobias",
1269 "year" : 2007
1270 },
1271 "child3" : {
1272 "name" : "Linus",
1273 "year" : 2011
1274 }
1275 }
1276
1277 print(myfamily)
1278
1279 # adding three dictionaries into one
1280 child1 = {
1281 "name" : "Emil",
1282 "year" : 2004
1283 }
1284 child2 = {
1285 "name" : "Tobias",
1286 "year" : 2007
1287 }
1288 child3 = {
1289 "name" : "Linus",
1290 "year" : 2011
1291 }
1292
1293 myfamily = {
1294 "child1" : child1,
1295 "child2" : child2,
1296 "child3" : child3
1297 }

localhost:52376/178a6b89-515c-48d4-81b2-a951d8109a59/ 27/27

You might also like