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
Q

Give me what the output will be of what these calculations will be:

print(3.0 + 3)
print(3.999 + 3)
print(3 - 2)

A

6.0
6.999000000000006
1

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

Give me what the output will be of what these calculations will be:

print(3 * 2)

print(3.0 * 2)

A

6
6.0

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

What is the power operator? (**) - (3)

A

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)

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

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)

A

27.0
3.0

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

raising to 1/something is the same as taking a root? So raising to 12 or 0.5 is the same

A

as taking the square root….

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

In Python 3, there are two ways to do division - (2)

A

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:

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

What is the output of this calculation code?

print(3 / 2)

print(3 // 2)

A

1.5
1

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

When using the integer division operator on floating point numbers, the division will be performed as though

A

the numbers were integer, but the result will be floating point:

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

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:

A

1.0

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

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:

A

1.0

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

What is modulus (‘%’) operator in Python? - (2)

A

It calculates the remainder of the division of the left operand by the right operand.

What is left over when you do the division

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

What is the output of this calculation?

print(8 % 3)

A

2

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

What error message will this code display?

print(3 + “dlfkjdofd”) # Go on, try it! - (2)

A

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.

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

print(3 + “dlfkjdofd”) gives error as

Adding a string and an integer does not make any sense and we get an - (3)

A

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.

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

Write a code working out your age in years in days - (4):

A

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)

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

What is output?

A

My age in years is: 22
My age in days in: 8030

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

What is precedence? - (2)

A

order in which operators are evaluated in an expression.

Operators with higher precedence are evaluated before operators with lower precedence.

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

Example of precedence: - (4)

A

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

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

The rules for precedence of mathematical operations in Python follow roughly the same rules as those in mathematics

A

(remember BODMAS)

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

Another example of precedence in Python

A

for instance: 1 + 2 * 3 will be evaluated as 1 + (2 * 3) giving a result of 7, because multiplication is higher precedence than addition.

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

In cases In Python where precedence is not correct, or you simply want to make your code clearer, you can use

A

brackets in the same way that you would in algebra.

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

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:

A

res = 1 + (2 * 3)
print(res)

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

What would the output be?

res = 1 + (2 * 3)
print(res)

A

7

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

In precedence in Python, brackets can also be nested if necessary for example:

A

res = 1 + (2 * (3 + 1))
print(res)

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

What would the output be?

res = 1 + (2 * (3 + 1))
print(res)

A

9

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

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)

A

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.

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

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

a list and a dictionary (which we will cover in the next session)

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

What are variable types that store collections of data? - (3)

A
  1. Lists
  2. Tuples
  3. Dictionaries
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
53
Q

What is a list? - ‘(4)

A

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 []

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

To create a list, we use

A

square brackets: [ ]

55
Q

What does this mean

my_list = []

A

empty list

56
Q

What would this code produce as output? - (4)

my_list = []

print(my_list)
print(type(my_list))

A

[]
<class ‘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
Q

What is ‘append()’ in Python? - (2)

A

It’s used to add an element to the end of the list.

adds a single value into the list

58
Q

Code so far:
my_list = []

Using append, add 100, 105 and 120 to list, print the list and check its length - (5)

A

my_list.append(100)
my_list.append(105)
my_list.append(120)

print(my_list)
print(len(my_list))

59
Q

give output :

my_list = []

my_list.append(100)
my_list.append(105)
my_list.append(120)

print(my_list)
print(len(my_list))

A

[100, 105, 120]
3

60
Q

2 sorts of functions in Python - (2)

A
  1. Standalone Functions
  2. Member functions
61
Q

What are standalone functions in Python? - (5)

A

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
Q

What are member functions? - (5)

A

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
Q

Example of standalone functions in Python - (2)

A

functionName(arguement 1, arguement 2,…)

functionName = print() or len()

64
Q

Examples of datastructure having member function layout

A

dataStructure.functionName (arguement 1,….)

function name = member function like append(_

65
Q

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

A

my_new_list = [‘ant’, ‘bear’, ‘hi’,10, 20,50,60, 5.234]

print(my_new_list)
print(len(my_new_list))

66
Q

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

A

use len to find the length of the variable.

Here it says we have three element in the list.

67
Q

Lists can contain

A

data of different types

68
Q

Example lists can contain data of different types - (3)

A

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
Q

In lists, we use commas to separate the

A

elements of the list

70
Q

lists can contain any types of data - including other

A

lists

71
Q

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)
A

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
Q

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)
A

[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
Q

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…

A

use .extend () member function

74
Q

Why is extend() useful?

A

combine the elements of two lists or add multiple elements to an existing list efficiently without creating a new list.

75
Q

What is output?

A

[1, 2, 3, 10, 20, 23, 12, 121211212, ‘skjdskdjls’]
9

76
Q

Python is a 0-indexed language. This means that - (2)

A

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
Q

How to extract individual elements of a list in Python?

A

We use these indices with the square brackets [NUMBER] to extract our values

78
Q

What is the output of this?

my_new_list = [‘ant’, ‘bear’, 10, 20]

print(my_new_list[0])

A

ant

79
Q

What is this output?

my_element = my_new_list[2]
print(my_element)
print(type(my_element))

A

10
<class ‘int’>

80
Q

Python also … indexing around negative numbers

A

wraps

81
Q

What is output?

my_new_list = [‘ant’, ‘bear’, 10, 20]

print(my_new_list[-2])

A

10 - ‘-2’ accessed second last element of the list

82
Q

What is output?

my_new_list = [‘ant’, ‘bear’, 10, 20]

print(my_new_list[-1])

A

20 = ‘-1’ as index accesses last element of list

83
Q

We can extract the element from the list and either - (2)

A

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
Q

We can also xtract a number of elements in one go. This gives us

A

shorter list

85
Q

The indexing notation for extracting multiple elements (in a list) uses a

The pattern is..

But since Python is 0-inddxed - (3)

A

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
Q

my_new_list = [‘ant’, ‘bear’, 10, 20]

print(my_new_list[1:3])

What does 1:3 mean and what is its output? - (3)

A

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
Q

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]))

A

[‘bear’, 10]
2
<class ‘list’>

88
Q

If we miss starting parameter in [start:stop] in extracting multiple items in list then, -

A

it defaults to 0, assuming the beginning of the list

89
Q

my_new_list = [‘ant’, ‘bear’, 10, 20]

print(my_new_list[:2])

What is its output?

A

[‘ant’, ‘bear’]

90
Q

If we miss stop parameter in [start:stop] in extracting multiple items in list then, -

A

It defaults the stop parameter at the end of the list

91
Q

What does my_new_list[:2] mean?

A

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
Q

What does my_new_list[2:] mean? - (2)

A

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
Q

my_new_list = [‘ant’, ‘bear’, 10, 20]

print(my_new_list[2:])

What is its output?

A

[10, 20]

94
Q

If we use the same stop and start parameter in [start:stop] in extracting multiple items in list then, -

A

we end up with an empty list ‘ [] ‘

95
Q

my_new_list = [‘ant’, ‘bear’, 10, 20]

print(my_new_list[1:1])

What is its output?

A

[]

96
Q

my_new_list = [ ‘ant’ , ‘bear’ , 10, 20]

my_data = my_new_list [0:2]

print(my_data)

A

[‘ant’ , ‘bear’]

97
Q

Other option in extracting many items in a list, aside from [start:stop] which is - (2)

A

[start:stop:step]

Python supports an optional third parameter, step, which specifies the step or increment between elements

98
Q

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)

A

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
Q

animals = [‘ant’, ‘bear’, ‘cat’, ‘deer’, ‘elk’, ‘frog’, ‘goose’, ‘horse’]

print(animals[:5:2])

Meaning of what [:5:2]) and output

A

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
Q

animals = [‘ant’, ‘bear’, ‘cat’, ‘deer’, ‘elk’, ‘frog’, ‘goose’, ‘horse’]

print(animals[1::2])

Meaning of what [1::2]) and output - (3)

A

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
Q

animals = [‘ant’, ‘bear’, ‘cat’, ‘deer’, ‘elk’, ‘frog’, ‘goose’, ‘horse’]

print(animals[::2])

Meaning of what [::2]) and output - (2)

A

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
Q

animals = [‘ant’, ‘bear’, ‘cat’, ‘deer’, ‘elk’, ‘frog’, ‘goose’, ‘horse’]

print(animals[::-1])

Meaning of what [::-1]) and output - (2)

A

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
Q

animals = [‘cat’, ‘dog’, ‘elephant’, ‘giraffe’, ‘hippo’, ‘lion’, ‘tiger’]

print(animals[::-2])

What is meaning and output? - (2)

A

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
Q

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)

A

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
Q

Two ways to remove elements from a list - (2)

A
  1. Pop
  2. del
106
Q

What is pop()? - (4)

A

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
Q

What is del()? - (3)

A

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
Q

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)

A

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
Q

Example of using del statement in code - (2)

A

my_list = [10, 20, 30, 40, 50]

del my_list[0]

110
Q

What is the sorted() function? - (2)

A

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
Q

What does this give as output?

A

[10, 20, 40, 50]
[50, 40, 10, 20]

112
Q

In sort () function, it is different from sorted() as it - (2)

A

It modifies the original list

sorts the original list ‘in place’

113
Q

2 ways to sort a list - (2)

A
  1. Sort()
  2. Sorted()
114
Q

Example of using sort()

A

[10, 20, 40, 50]

115
Q

What is count() function?

A

a built-in method of lists in Python that returns the number of occurrences of a specified element in the list.

116
Q

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)

A

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
Q

count() is a

A

member function!

118
Q

Types of data structures in Python - (5)

A
  1. Lists
  2. Tuples
  3. Dictionaries
  4. Sets
  5. Strings
  6. Arrays
119
Q

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:

A

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
Q

What are tuples? - (2)

A

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
Q

What is difference between tuples and lists? - (2)

A

tuples ‘()’

whereas lists use ‘[]’

122
Q

We can create an empty tuple using

A

round brackets ()

123
Q

The problem with creating an empty tuple is that

A

hey cannot be changed - this therefore means that it will remain empty forever!

124
Q

What would this piece of code output to console?

a = ( )

print(type(a))
print(a)

A

<class ‘tuple’>
()

125
Q

Instead of an empty tuple, more commonly we produce

A

a tuple with existing content:

126
Q

A tuple with existing content for example

What would this piece of code output to console?

a = (1, 2, 3)

print(a)

A

(1, 2, 3)

127
Q

Other than tuples being unchangeable (‘immutable’), tuples behave like

A

extract items and count the length of a tuple in the same way that you can with lists

128
Q

Code:

my_tuple = (5, 10, 15)

print(my_tuple[1])

print(len(my_tuple))

Output?

A

10
3

129
Q

If you try and change an item in a tuple, you will get a

A

TypeError exception

130
Q

Code:
my_tuple = (5, 10, 15)

my_tuple[0] = 100

Output - (2)

A

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
Q

if you have a tuple which you need to modify, you can

A

you can cast it to (turn it into) a list and back again

132
Q

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)

A

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
Q
A