Introduction to Programming - 2 Flashcards

1
Q

Variables can be of different types

Type of a variable tells you…. which is important as.. - (2)

A

what the computer thinks it is

This is important because it does not make sense, for example, to multiply two strings. What would “apples”*“pears” mean

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

What are the 4 main data types for variables?

A
  1. Numbers
  2. String
  3. Boolean
  4. None
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

Two variable data types inside Number type is - (2)

A

Integer
Floating point

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

What is ‘int’ or integer variable data type and example? - (2)

A

a whole number – can be positive or negative: … -2, -1, 0, 1, 2 …)

e.g., number of people in a experimental condition

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

What is ‘float’ or floating point variable data type and example? - (2)

A

a decimal number: e.g. 3.14159)

e.g., reaction times (RTs)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

What is a string variable data type and example? - (3)

A

A string is a sequence of characters, enclosed within quotation marks, that can include letters, numbers, symbols, and spaces.

It can be of zero or more characters in lengthzero or more characters

(e.g. “Hello World”)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

What is a Boolean variable data type?

A

A boolean variable is a data type that can hold one of two values: True or False

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

What is none variable data type?

A

None type – this is a special name for nothing in Python which is useful in various contexts.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

Example of using ‘none’

A

x = None

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

What is ‘type’ function? - (3)

A

examine a variable or a thing we type into the console.

“type” refers to the classification of an object. Every object in Python has a type, which determines what kind of operations can be performed on that object and how it behaves.

determine the type of an object

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

What is the output?

A

<class ‘int’>
Type of type(3) is <class ‘int’>
Type of type(3.0) is <class ‘float’>
Type of type(“3.0”) is <class ‘str’>
Type of type(None) is <class ‘NoneType’>
Type of type(True) is <class ‘bool’>
Type of type(False) is <class ‘bool’>

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

In first line, we print the return value of…

To make things clearer… - (2)

A

return value of the type function

To make things clearer, on the other lines we add some extra information to help with context.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

Write a code that stores values into a,b and c and asks its type

A

a = 3
print(‘Type of a is’, type(a))

b = 3.0
print(‘Type of b is’, type(b))

c = “Hello World”
print(‘Type of c is’, type(c))

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

What is output?

a = 3
print(‘Type of a is’, type(a))

b = 3.0
print(‘Type of b is’, type(b))

c = “Hello World”
print(‘Type of c is’, type(c))

A

Type of a is <class ‘int’>
Type of b is <class ‘float’>
Type of c is <class ‘str’>

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

if we have a variable in a script which we do not know the type of (for example, something that was returned from a function which we did not write), we can ask the script to tell us using

A

the type function and use {x} in Collab

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

Note that python makes numbers int by default unless

A

they have a decimal point in them

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
17
Q

Most of the time, you will want float numbers so it is good practice to add a .0 to the end

Alternatively to adding .0, we can:

A

pass it through the float function

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
18
Q

We can also turn floating point number into integer using int function which will

Note… - (3)

A

this will lose any floating point part of the number

Note that this does not “round” the number properly, it simply truncates it and chops off end of number (i.e., decimals).

Usually int operator forcing a floating point number to be a integer is something you dont want as it’s a common way for new Python programmers to generate bugs

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
19
Q

Write code that will turn/cast/convert integer 3 into float and also another line of code that turns 3.25 into integer - (2)

A

print(type(float(3)))

print(type(int(3.25)))

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
20
Q

What is the output of this code? - (4)

print(type(float(3)))

print(type(int(3.25)))

print(int(3.25))

print(int(3.999))

A

<class ‘float’>
<class ‘int’>
3
3

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
21
Q

What are arithmetic operators in Python?

A

used to perform mathematical operations on numeric operands.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
22
Q

What are the arithmetic operators in Python? - (7)

A
  1. Addition (‘+’)
  2. Subtraction (‘ - ‘ )
  3. Multiplication (‘*’)
  4. Divison (‘/’)
  5. Integer Divison (‘//’)
  6. Power (**)
    7.Modulus/Reminder (‘%’)
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
23
Q

What if you mix up data types of numbers?

A

they tend to become floating numbers in calculations

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
24
Q

if you do calculations of the same type they tend to become

A

the same time data type

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
25
Give me what the output will be of what these calculations will be: print(3.0 + 3) print(3.999 + 3) print(3 - 2)
6.0 6.999000000000006 1
26
Give me what the output will be of what these calculations will be: print(3 * 2) print(3.0 * 2)
6 6.0
27
What is the power operator? (**) - (3)
used for exponentiation, meaning raises the left operand to the power of the right operand e.g., 5 **3 is 5 raised to the power of 3 used to compute both "normal" power values (like squaring)
28
What is the output of this code? print(3.0 ** 3) # 3 to the power of 3 print(9.0 ** 0.5) # 9 to the power of 0.5 (The square root of 9)
27.0 3.0
29
raising to 1/something is the same as taking a root? So raising to 12 or 0.5 is the same
as taking the square root....
30
In Python 3, there are two ways to do division - (2)
The first one (/) allows integers to turn into floating point numbers 'where necessary' (in other words, if the answer is not an integer). The alternative integer division operator (//) does not and produces integer result:
31
What is the output of this calculation code? print(3 / 2) print(3 // 2)
1.5 1
32
When using the integer division operator on floating point numbers, the division will be performed as though
the numbers were integer, but the result will be floating point:
33
When using the integer division operator on floating point numbers, the division will be performed as though the numbers were integer, but the result will be floating point: For example: print(3.0//2) gives you:
1.0
34
When using the integer division operator on floating point numbers, the division will be performed as though the numbers were integer, but the result will be floating point: For example: print(3.0//2.0) gives you:
1.0
35
What is modulus ('%') operator in Python? - (2)
It calculates the remainder of the division of the left operand by the right operand. What is left over when you do the division
36
What is the output of this calculation? print(8 % 3)
2
37
What error message will this code display? print(3 + "dlfkjdofd") # Go on, try it! - (2)
return the error message of 'unsupported operand type(s) for +: 'int' and 'str' This tells you that you can only concatenate strings to strings - adding an integer on doesn't make any sense.
38
print(3 + "dlfkjdofd") gives error as Adding a string and an integer does not make any sense and we get an - (3)
This just means an error an exceptional event occurred that the computer cannot cope with. The traceback (information in the exception) will normally give you a good hint as to what is wrong. In this case, it tells you that you can only concatenate strings to strings - adding an integer on doesn't make any sense.
39
Write a code working out your age in years in days - (4):
age_in_years = 22 days_per_year = 365 print("My age in years is:" ,age_in_years) print("My age in days in:", age_in_years*days_per_year)
40
What is output?
My age in years is: 22 My age in days in: 8030
41
What is precedence? - (2)
order in which operators are evaluated in an expression. Operators with higher precedence are evaluated before operators with lower precedence.
42
Example of precedence: - (4)
For example, consider the expression 3 + 4 * 5. In Python, the * operator has higher precedence than the + operator. Therefore, the multiplication operation 4 * 5 is evaluated first, and then the addition operation 3 + (result of 4 * 5) is performed. As a result, the expression evaluates to 23
43
The rules for precedence of mathematical operations in Python follow roughly the same rules as those in mathematics
(remember BODMAS)
44
Another example of precedence in Python
for instance: 1 + 2 * 3 will be evaluated as 1 + (2 * 3) giving a result of 7, because multiplication is higher precedence than addition.
45
In cases In Python where precedence is not correct, or you simply want to make your code clearer, you can use
brackets in the same way that you would in algebra.
46
In cases where precedence is not correct, or you simply want to make your code clearer, you can use brackets in the same way that you would in algebra. So, for instance you can write 1+ 2 * 3 the above as:
res = 1 + (2 * 3) print(res)
47
What would the output be? res = 1 + (2 * 3) print(res)
7
48
In precedence in Python, brackets can also be nested if necessary for example:
res = 1 + (2 * (3 + 1)) print(res)
49
What would the output be? res = 1 + (2 * (3 + 1)) print(res)
9
50
Having variables (or 'boxes') where you can store single numbers or strings is useful, but we quite often want to deal with more than a single piece of data. For example, - (2)
we might have a list of reaction times from an experiment we did on lots of different people, or a list containing the names (or, better, the anonymised ID numbers) of those people. Alternatively, we might have information such as "this person has this phone number" for a lot of people.
51
To store collections of data like this, we have access to a set of variable types designed to make it easy. The trick is learning which one to use at which time. You will often choose between a
a list and a dictionary (which we will cover in the next session)
52
What are variable types that store collections of data? - (3)
1. Lists 2. Tuples 3. Dictionaries
53
What is a list? - '(4)
Lists are ordered collections of items. They are mutable, meaning you can modify the elements after creation. Lists can contain elements of different data types, and elements can be accessed by their index. Lists are created using square brackets []
54
To create a list, we use
square brackets: [ ]
55
What does this mean my_list = []
empty list
56
What would this code produce as output? - (4) my_list = [] print(my_list) print(type(my_list))
[] You will see that when we print the list, the square brackets are used to indicate to us that we are looking at a list in the output. As before, using type shows us the type or 'class' of the variable - unsurprisingly, it is a list.
57
What is 'append()' in Python? - (2)
It's used to add an element to the end of the list. adds a single value into the list
58
Code so far: my_list = [] Using append, add 100, 105 and 120 to list, print the list and check its length - (5)
my_list.append(100) my_list.append(105) my_list.append(120) print(my_list) print(len(my_list))
59
give output : my_list = [] my_list.append(100) my_list.append(105) my_list.append(120) print(my_list) print(len(my_list))
[100, 105, 120] 3
60
2 sorts of functions in Python - (2)
1. Standalone Functions 2. Member functions
61
What are standalone functions in Python? - (5)
These are functions that operate on arguments you pass to them. If the arguments are 'butter, eggs and sugar' then the function is a blender They're like standalone tools that you can use on various sets of data Examples include built-in functions like len(), print(), sum(), etc Just like a blender can blend different ingredients, these functions can operate on different types of data
62
What are member functions? - (5)
These are methods that are built into specific data structures. They are tailor-made to work with and manipulate the data contained within those structures. Examples include methods like append() for lists, update() for dictionaries, join() for strings, etc These are like little toolkits built in to a data structure that are specifically crafted to do things to that data (e.g., append). Like a little tookit that is built in to a bike or a cleaning set built in to a sewing machine.
63
Example of standalone functions in Python - (2)
functionName(arguement 1, arguement 2,...) functionName = print() or len()
64
Examples of datastructure having member function layout
dataStructure.functionName (arguement 1,....) function name = member function like append(_
65
Write a code that as a list variable called my_new_list which contains: ant, bear, hi, 10,20,50,60,5.234 Prints it and finds length of the variable
my_new_list = ['ant', 'bear', 'hi',10, 20,50,60, 5.234] print(my_new_list) print(len(my_new_list))
66
What does len function do in this code? my_new_list = ['ant', 'bear', 'hi',10, 20,50,60, 5.234] print(my_new_list) print(len(my_new_list)) Output: ['ant', 'bear', 'hi', 10, 20, 50, 60, 5.234] 8
use len to find the length of the variable. Here it says we have three element in the list.
67
Lists can contain
data of different types
68
Example lists can contain data of different types - (3)
my_new_list = ['ant', 'bear', 'hi',10, 20,50,60, 5.234] the first two elements are strings, and the next two are integers As usual, our strings have to be declared using quotes (in this case we used ', but we could equally well have used ").
69
In lists, we use commas to separate the
elements of the list
70
lists can contain any types of data - including other
lists
71
Explain this code of append a list to another list: my_main_list = [1, 2, 3] my_other_list = [10, 20] my_main_list.append(my_other_list) print(my_main_list) print(len(my_main_list)) - (5)
Main list containing 1,2,3 Other list containing 10 and 20 You add/append other_list to my main list You print out my main list You then check its length
72
What output will it give and why give 4 as len? - (2) my_main_list = [1, 2, 3] my_other_list = [10, 20] my_main_list.append(my_other_list) print(my_main_list) print(len(my_main_list)) - (5)
[1, 2, 3, [10, 20]] 4 = returns 4 since [10,20] is a single item in the list All sorts of things could have happened here - for example, the new list might have just been [1,2,3,10,20]. But no! Instead, we see that appending the list into the list has added one new element That element it itself a list.
73
my_main_list = [1, 2, 3] my_other_list = [10, 20] my_main_list.append(my_other_list) #appending, adding one list to another , adding '[10,20]# print(my_main_list) print(len(my_main_list)) # returns 4 since [10,20] is a single item Output: [1, 2, 3, [10, 20]] 4 To make list [1,2,3,10,20] then...
use .extend () member function
74
Why is extend() useful?
combine the elements of two lists or add multiple elements to an existing list efficiently without creating a new list.
75
What is output?
[1, 2, 3, 10, 20, 23, 12, 121211212, 'skjdskdjls'] 9
76
Python is a 0-indexed language. This means that - (2)
the first element in any sequence (including lists) is called the 'zeroth' element and not the 'first' element. This means that the valid indices for our list of length 4 are: 0, 1, 2, 3
77
How to extract individual elements of a list in Python?
We use these indices with the square brackets [NUMBER] to extract our values
78
What is the output of this? my_new_list = ['ant', 'bear', 10, 20] print(my_new_list[0])
ant
79
What is this output? my_element = my_new_list[2] print(my_element) print(type(my_element))
10
80
Python also ... indexing around negative numbers
wraps
81
What is output? my_new_list = ['ant', 'bear', 10, 20] print(my_new_list[-2])
10 - '-2' accessed second last element of the list
82
What is output? my_new_list = ['ant', 'bear', 10, 20] print(my_new_list[-1])
20 = '-1' as index accesses last element of list
83
We can extract the element from the list and either - (2)
pass it straight to print (or any other function). Alternatively, we can extract the element and place it into a variable (called my_element in this case
84
We can also xtract a number of elements in one go. This gives us
shorter list
85
The indexing notation for extracting multiple elements (in a list) uses a The pattern is.. But since Python is 0-inddxed - (3)
colon : The pattern is [start:stop], but as Python is 0-indexed and end-points are exclusive bold text, the element which has the last number will not be included.
86
my_new_list = ['ant', 'bear', 10, 20] print(my_new_list[1:3]) What does 1:3 mean and what is its output? - (3)
Output: ['bear', 10] Meaning: Extract 1:3, meaning elements 1 and 2 but not 3rd one starting from index 1 up to, but not including, index 3.
87
What is the output? my_new_list = ['ant', 'bear', 10, 20] print(my_new_list[1:3]) print(len(my_new_list[1:3])) print(type(my_new_list[1:3]))
['bear', 10] 2
88
If we miss starting parameter in [start:stop] in extracting multiple items in list then, -
it defaults to 0, assuming the beginning of the list
89
my_new_list = ['ant', 'bear', 10, 20] print(my_new_list[:2]) What is its output?
['ant', 'bear']
90
If we miss stop parameter in [start:stop] in extracting multiple items in list then, -
It defaults the stop parameter at the end of the list
91
What does my_new_list[:2] mean?
Python interprets it as extracting elements from the beginning of the list up to (but not including) the element at index 2. In other words, it starts from index 0 and goes up to, but does not include, index 2.
92
What does my_new_list[2:] mean? - (2)
Python interprets it as extracting elements starting from index 2 (inclusive) up to the end of the list. In other words, it starts from index 2 and goes all the way to the end of the list.
93
my_new_list = ['ant', 'bear', 10, 20] print(my_new_list[2:]) What is its output?
[10, 20]
94
If we use the same stop and start parameter in [start:stop] in extracting multiple items in list then, -
we end up with an empty list ' [] '
95
my_new_list = ['ant', 'bear', 10, 20] print(my_new_list[1:1]) What is its output?
[]
96
my_new_list = [ 'ant' , 'bear' , 10, 20] my_data = my_new_list [0:2] print(my_data)
['ant' , 'bear']
97
Other option in extracting many items in a list, aside from [start:stop] which is - (2)
[start:stop:step] Python supports an optional third parameter, step, which specifies the step or increment between elements
98
animals = ['ant', 'bear', 'cat', 'deer', 'elk', 'frog', 'goose', 'horse'] print(animals[1:5:2]) What does 1:5:2 mean and what is its output? - (3)
Meaning: # Extract every other item starting at index 1 and finishing at index 5 start at 1 and finish at 5 don't include 5 and go in steps of 2 Output: ['bear', 'deer']
99
animals = ['ant', 'bear', 'cat', 'deer', 'elk', 'frog', 'goose', 'horse'] print(animals[:5:2]) Meaning of what [:5:2]) and output
Meaning: it will extract elements from index 0 (assume it will start at beginning of list) since no start parameter up to (but not including) index 5 with a step size of 2. Output: ['ant', 'cat', 'elk']
100
animals = ['ant', 'bear', 'cat', 'deer', 'elk', 'frog', 'goose', 'horse'] print(animals[1::2]) Meaning of what [1::2]) and output - (3)
Meaning: it will extract elements starting from index 1 up to the end of the list with a step size of 2 Has no stop parameter so assume it will extract items until end of list Output: ['bear', 'deer', 'frog', 'horse']
101
animals = ['ant', 'bear', 'cat', 'deer', 'elk', 'frog', 'goose', 'horse'] print(animals[::2]) Meaning of what [::2]) and output - (2)
Meaning: it will extract elements from the beginning of the list (assume since no start parameter is specificed) up to the end of the list (assume since no stop parameter is specificed) with a step size of 2 Output: ['ant', 'cat', 'elk', 'goose']
102
animals = ['ant', 'bear', 'cat', 'deer', 'elk', 'frog', 'goose', 'horse'] print(animals[::-1]) Meaning of what [::-1]) and output - (2)
Meaning: it will extract elements from the end of the list to the beginning of the list with a step size of -1, effectively reversing the list. Output: ['horse', 'goose', 'frog', 'elk', 'deer', 'cat', 'bear', 'ant']
103
animals = ['cat', 'dog', 'elephant', 'giraffe', 'hippo', 'lion', 'tiger'] print(animals[::-2]) What is meaning and output? - (2)
Meaning: animals[::-2], it will start from the end of the list, select every second element, and stop at the beginning of the list Output: ['tiger', 'hippo', 'elephant', 'cat']
104
Some banks ask for a small subset of your 'special number' for verification purpose. Change the code below so that it prints out every third number starting with the first one - (4) Code Then Output Original Code to Change: my_special_number = ['1','5','2','7','9','2','3','8','8'] numbers_requested=my_special_number[x:x:x] print(numbers_requested)
Code: my_special_number=['1','5','2','7','9','2','3','8','8'] numbers_requested=my_special_number[0:8:3] # or write it as [0::3] or [::3], print(numbers_requested) Output: ['8', '8', '3', '2', '9', '7', '2', '5', '1']
105
Two ways to remove elements from a list - (2)
1. Pop 2. del
106
What is pop()? - (4)
The pop() method removes and returns the item at the specified index (by default, the last item) from the list. It modifies the original list in place. You can also specify an index as an argument to pop() to remove an item at a specific index. If no index is specified and the list is empty, pop() raises an IndexError.
107
What is del()? - (3)
The del statement removes an item or slice from a list based on its index or slice notation. It doesn't return the removed item(s); it just removes them from the list. It modifies the original list in place.
108
my_list = [10, 20, 30, 40, 50] print(my_list) thing_removed = my_list.pop(2) print(thing_removed) What is its output and meaning - (5)
Meaning: Prints my_list content my_list.pop(2) will remove the item at index 2 from my_list and stores is thing_removed variable It will then print thing_removed which will return the item that was taken from my_list using my_list.pop(2) Output: [10, 20, 30, 40, 50] 30
109
Example of using del statement in code - (2)
my_list = [10, 20, 30, 40, 50] del my_list[0]
110
What is the sorted() function? - (2)
sort iterables (such as lists, tuples, or strings) into a new sorted list. It does not modify the original iterable (The original list variable remains unchanged.); instead, returns a new copy of the list which has been sorted
111
What does this give as output?
[10, 20, 40, 50] [50, 40, 10, 20]
112
In sort () function, it is different from sorted() as it - (2)
It modifies the original list sorts the original list 'in place'
113
2 ways to sort a list - (2)
1. Sort() 2. Sorted()
114
Example of using sort()
[10, 20, 40, 50]
115
What is count() function?
a built-in method of lists in Python that returns the number of occurrences of a specified element in the list.
116
Give output and meaning to the code below: my_list = [10, 20, 20, 30, 30, 30] print(my_list.count(20)) # counts the number ' 20s' print(my_list.count(30)) # counts the number of '30s' print(my_list.count(50)) #Trick questions! There >is< no number 50 in the list - (5)
Meaning: it first counts the occurences of '20's in list Then counts the occurences of '30's in list Then counts the number of '50's in list but there is no number '50' It is search for an element which doesn't exist - in that case, the .count member function returns 0 Output: 2 3 0
117
count() is a
member function!
118
Types of data structures in Python - (5)
1. Lists 2. Tuples 3. Dictionaries 3. Sets 4. Strings 5. Arrays
119
Coding Exercise: Write a script in which you store a set of fifteen scores out of 5 from an experiment (make up the scores and manually put them in a list). Print out your list, then sort the list and print it again. Finally, print out the number of people who scored 0, 1, 2, 3, 4 and 5. Write code and its output:
my_list = [0,2,4,1,3,4,5,2,3,4,2,3,1,0,2] print(my_list) my_list.sort() print(my_list) print(my_list.count(0)) print(my_list.count(1)) print(my_list.count(2)) print(my_list.count(3)) print(my_list.count(4)) print(my_list.count(5)) Output: [0, 2, 4, 1, 3, 4, 5, 2, 3, 4, 2, 3, 1, 0, 2] [0, 0, 1, 1, 2, 2, 2, 2, 3, 3, 3, 4, 4, 4, 5] 2 2 4 3 3 1
120
What are tuples? - (2)
Tuples are similar to lists, but they are immutable, meaning once created, their elements cannot be changed (i.e., you can not change, add or remove items to/from a tuple) Tuples are created using parentheses ()
121
What is difference between tuples and lists? - (2)
tuples '()' whereas lists use '[]'
122
We can create an empty tuple using
round brackets ()
123
The problem with creating an empty tuple is that
hey cannot be changed - this therefore means that it will remain empty forever!
124
What would this piece of code output to console? a = ( ) print(type(a)) print(a)
()
125
Instead of an empty tuple, more commonly we produce
a tuple with existing content:
126
A tuple with existing content for example What would this piece of code output to console? a = (1, 2, 3) print(a)
(1, 2, 3)
127
Other than tuples being unchangeable ('immutable'), tuples behave like
extract items and count the length of a tuple in the same way that you can with lists
128
Code: my_tuple = (5, 10, 15) print(my_tuple[1]) print(len(my_tuple)) Output?
10 3
129
If you try and change an item in a tuple, you will get a
TypeError exception
130
Code: my_tuple = (5, 10, 15) my_tuple[0] = 100 Output - (2)
TypeError: 'tuple' object does not support item assignment you'll encounter the TypeError because tuples do not allow item assignment. Tuples are designed to be immutable to ensure that the data they represent remains unchanged throughout the program execution
131
if you have a tuple which you need to modify, you can
you can cast it to (turn it into) a list and back again
132
Example of code modifying tuple by casting it back to list - (5) my_orig_tuple = (1, 2, 3, 4) my_tmp_list = list(my_orig_tuple) my_tmp_list[0] = 100 my_new_tuple = tuple(my_tmp_list) print(my_orig_tuple) print(my_new_tuple)
Initially, a tuple named my_orig_tuple is defined with values (1, 2, 3, 4) Then, the tuple is converted into a list named my_tmp_list using the list() function to enable modifications. The first element of the list is then changed to 100, effectively altering the original tuple indirectly Finally, the modified list is converted back to a tuple named my_new_tuple using the tuple() function, preserving the original tuple-like structure but with the desired change applied. The print() statements demonstrate that the original tuple remains unchanged, while the modified tuple reflects the alteration
133