Session 1 - Part 2 Flashcards

1
Q

What are collections of data in Python?

A

Collections of data in Python are structures designed to store multiple pieces of information.

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

What are the different types of collections of data in Python? - (3)

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

What are lists - (2)?

A

A list is a collection of data that is ordered and changeable.

It allows you to store multiple items in a single variable.

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

What is the main difference between a list and a dictionary in Python?

A

The main difference between a list and a dictionary in Python is that a list is ordered and accessed by index, while a dictionary is unordered and accessed by key.

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

What are some examples of when you might use a list in Python?

A

You might use a list in Python to store a series of numbers, a list of names, or the results of an experiment involving multiple trials or participants.

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

How are elements accessed in a list compared to a dictionary in Python?

A

In a list, elements are accessed by their index position, starting from 0. In a dictionary, elements are accessed by their key.

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

How do you create an empty list in Python? - (2)

A

An empty list in Python can be created using square brackets:

e.g., my_list = []

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

What function can you use to determine the type of a variable in Python?

A

The type() function can be used to determine the type or class of a variable in Python.

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

What does the following code snippet create and print?

my_list = []
print(my_list)
print(type(my_list)) - (2)

A

The code creates an empty list named my_list and prints the list [].

It also prints the type of the variable my_list, which is list.

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

How do you add elements to a list in Python?

A

Elements can be added to a list in Python using the ‘append’ member function

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

What is the purpose of the append() method in Python?

A

The append() method in Python is used to add elements to the end of a list.

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

What does the len() function return when applied to a list?

A

The len() function returns the number of elements in a list when applied to that list in Python.

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

What does the following code snippet do? - (2)

my_list = []
my_list.append(100)
my_list.append(105)
my_list.append(120)
print(my_list)
print(len(my_list))

A

The code creates an empty list named my_list and appends the integers 100, 105, and 120 to it.

Output: Then it prints the list [100, 105, 120] and the length of the list, which is 3

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

What are member functions in Python? - (2)

A

Member functions are built-in functions specific to a data structure that allow operations to be performed on that data.

They are called using the syntax: dataStructure.functionName(argument1, …).

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

What is the purpose of the append() member function in Python lists?

A

The append() member function adds a single value to the end of a list.

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

We can use append() many times to add many

A

elements to a list

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

‘len’ is a normal function and ‘append’ is a

A

member function

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

Produce a list that contain elements from start and use

A

commas to separate the elements

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

Lists can contain data of

A

different types

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

Example of list containing different data types - (3)

A

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

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 “).

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

What is the purpose of using quotes when declaring strings within a list? - (2)

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

A

Quotes (either single or double) are used to denote string literals within a list.

This helps Python distinguish between string values and other types of data. In the given example, strings like ‘ant’, ‘bear’, and ‘hi’ are enclosed in single quotes to indicate they are string elements of the list.

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

What will be the output of the code snippet provided? - (4)

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

print(my_new_list)
print(len(my_new_list))

A

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

The print(my_new_list) statement will display the contents of the my_new_list list, including strings and integers.

The print(len(my_new_list)) statement will output the length of the list, which is 8, indicating the total number of elements present in the list.

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

What happens when you append a list to another list in Python?

A

When you append a list to another list using the append() member function, the entire second list becomes a single element of the first list.

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

What will be the output of print(my_main_list) after appending my_other_list to it?

my_main_list = [1, 2, 3]
my_other_list = [10, 20]
my_main_list.append(my_other_list)

  • (2)
A

The output of print(my_main_list) will include my_other_list as a single element within my_main_list, preserving its structure

Output: [1, 2, 3, [10, 20]] and 4

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

Question: What does the following Python code snippet do? - (4)

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

A

This code snippet initializes two lists, my_main_list and my_other_list, with some integer values.

Then, it appends my_other_list as a single element to my_main_list, resulting in my_main_list containing four elements: [1, 2, 3, [10, 20]].

Finally, it prints my_main_list and its length using the len() function.

Since my_main_list is
[1,2,3 [10,20]]) , the length of my_main_list is 4.

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

What is the difference between using .append() and .extend() to add elements from one list to another in Python? - (2)

A

When using .append(), the entire second list is added as a single element to the first list.

In contrast, when using .extend(), each element of the second list is added individually to the first list.

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

How can we add multiple elements from an existing list to another/our new list in Python?

A

Multiple elements from one list can be added to another list in Python using the .extend() member function.

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

Why might it be useful to use the .extend() function instead of the .append() function when working with lists in Python?

A

It might be useful to use the .extend() function instead of the .append() function when working with lists in Python because it allows adding each element of one list individually to another list, rather than adding the entire second list as a single element.

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

print or len works this way:

A

functionName(arguement 1, arguement 2)

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

Once we have a list, one of the obvious things that we want to be able to do is

A

access individual elements of the list.

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

What does it mean for Python to be a 0-indexed language?

A

In Python, being a 0-indexed language means that the first element in any sequence, including lists, is referred to as the “zeroth” element, and indexing starts from 0 rather than 1.

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

How do you access individual elements of a list in Python?

A

Individual elements of a list in Python are accessed using square brackets [], with the index of the desired element inside the brackets.

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

What are the valid indices for a list of length 4 in Python?

A

For a list of length 4 in Python, the valid indices are 0, 1, 2, and 3.

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

: What is the output of the given code snippet? - (4)

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

print(my_new_list[0])

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

A

The code initializes a list my_new_list containing four elements: ‘ant’, ‘bear’, 10, and 20.

It then prints the first element of the list (‘ant’).

Next, it assigns the third element of the list (10) to the variable my_element and prints its value.

Finally, it prints the data type of my_element, which is <class ‘int’>

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

Change the code you just saw (we repeat it again below for you) to set ‘my_element’ to the first entry in the list. What is the type now? - (5)

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

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

A

To set my_element to the first entry in my_new_list, replace xxxx with 0 in the code.

The type of my_element will be <class ‘str’> because it will contain the string ‘ant’, which is the first entry in the list my_new_list.

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

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

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

We can extract the element from the list and pass it

A

print (or other function)

OR

extract elements and put it in a variable

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

How can you modify an element in a list in Python?

A

An element in a list in Python can be modified using square bracket indexing syntax, where you specify the index of the element to be modified and assign it a new value.

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

What is output of the code snippet below? - (3)

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

print(my_new_list)

my_new_list[2] = ‘Hello’

print(my_new_list)

A

[‘ant’, ‘bear’, 10, 20]
[‘ant’, ‘bear’, ‘Hello’, 20]

The first print statement displays the original list [‘ant’, ‘bear’, 10, 20], and the second print statement displays the modified list after changing the third element to ‘Hello’.

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

What does the code my_new_list[2] = ‘Hello’ do?

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

print(my_new_list)

my_new_list[2] = ‘Hello’

print(my_new_list)

A

The code my_new_list[2] = ‘Hello’ replaces the third element in the list my_new_list with the string ‘Hello’.

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

The square bracket indexing syntax in lists can also be used to modify

A

an element in a list

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

note that Python wraps

A

indexing around with negative numbers.

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

How can you access elements from the end of a list in Python? - (2)

A

In Python, you can access elements from the end of a list using positive indices or by using negative indices.

For example, -1 refers to the last element, -2 refers to the second-to-last element, and so on.

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

What does the code print(my_new_list[-1]) do? - (2)

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

print(my_new_list[-1])

print(my_new_list[-2])

A

The code print(my_new_list[-1]) prints the last element of the list my_new_list.

This is achieved by using a negative index -1, which refers to the last element of the list.

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

What is the output of the code snippet provided?

print(my_new_list[-1]) do? - (2)

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

print(my_new_list[-1])

print(my_new_list[-2])

A

20
10

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

What does the second print statement in the code snippet print(my_new_list[-2]) - (2)

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

print(my_new_list[-1])

print(my_new_list[-2])

A

The second print statement in the code snippet print(my_new_list[-2]) prints the second-to-last element of the list my_new_list.

This is achieved by using a negative index -2, which refers to the element before the last element of the list.

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

What does the indexing notation [start:stop] in Python lists mean? - (2)

A

The indexing notation [start:stop] in Python lists is used to extract multiple elements from a list.

It specifies a range of indices from the start index (inclusive) to the stop index (exclusive), and returns a sublist containing the elements within that range.

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

The indexing notation for extracting multiple elements of list uses a

A

colon ‘:’

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

The indexing notation for extracting multiple elements of list uses a colon and its pattern is

A

[start:stop]

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

as Python is 0-indexed and end-points are exclusive bold text, the element

A

which has the last number will not be included

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

Explain the output of the given code snippet.

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

Extract 1:3, meaning elements 1 and 2. Print the data and the length
print(my_new_list[1:3])
print(len(my_new_list[1:3]))
print(type(my_new_list[1:3]))

A

The code extracts elements at index 1 and 2 from my_new_list, prints the extracted elements ([‘bear’, 10]), their length (2), and their data type (<class ‘list’>).

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

Flashcard 3:
Missing start parameter in list slicing

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

If we miss out the start parameter, the beginning of the list is presumed
print(my_new_list[:2]) # assumes start parameter is 0

Explain the output of the given code snippet – (2)

A

The code slices my_new_list from the beginning up to index 2 (exclusive), effectively extracting elements at index 0 and 1.

It prints [‘ant’, ‘bear’], assuming the start parameter as 0 when not explicitly provided.

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

Missing stop parameter in list slicing

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

If we miss out the stop parameter, the end of the list is presumed
print(my_new_list[2:]) # assuming going right at end, 0 , 1, 10, 20

Describe the output of the given code snippet. - (2)

A

The code slices my_new_list from index 2 to the end, effectively extracting elements starting from index 2 to the end of the list.

It prints [10, 20], assuming the stop parameter is at the end of the list when it’s not explicitly provided.

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

Using the same number as start and stop in list slicing - (2)

python
Copy code
my_new_list = [‘ant’, ‘bear’, 10, 20]

If we use the same number as start and stop, we end up with an empty list
print(my_new_list[1:1]) # ‘[]’

What is the output of the given code snippet and why?

A

The code attempts to slice my_new_list from index 1 to index 1, resulting in an empty list [].

This happens because when the start and stop parameters are the same, no elements are included in the slice.

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

Assigning sliced data to a variable

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

Extract 0:2, meaning elements 0 and 1. Put in a variable
my_data = my_new_list[0:2]

print(my_data)

What does the given code snippet do? - (2)

A

The code extracts elements at index 0 and 1 from my_new_list and assigns them to a new variable my_data.

It then prints the content of my_data, which would be [‘ant’, ‘bear’]

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

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

print(my_new_list[0:2])

We can assign it to a variable like

A

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

my_data = my_new_list[0:2]

print(my_data)

56
Q

What does step parameter indicate in list slicing? [start:stop:step] - (2)

A

The step parameter in list slicing indicates the increment between each index when extracting elements from a list.

It allows for skipping elements based on the specified step size.

57
Q

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

Extract every other item starting at index 1 and finishing at index 5
print(animals[1:5:2]) # start at 1 and finish at 5, exclude 5, go in steps of 2

Describe the output of the given code snippet.

A

The code extracts every other item from index 1 to index 5 (exclusive) in the animals list and prints the result: [‘bear’, ‘deer’].

58
Q

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

We can miss out the start index and get everything from the start of the list
print(animals[:5:2])

What does the code snippet do, and what is its output? - (2)

A

The code slices animals from the beginning (0
-assumed) up to index 5 (exclusive) in steps of 2, effectively extracting every other item from the start of the list.

It prints the result: [‘ant’, ‘cat’, ‘elk’].

59
Q

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

We can miss out the stop index and get everything to the end of the list
print(animals[1::2])

Question: Explain the output of the given code snippet. - (2)

A

he code slices animals from index 1 to the end of the list in steps of 2, effectively extracting every other item starting from index 1.

It prints the result: [‘bear’, ‘deer’, ‘frog’, ‘horse’].

60
Q

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

We can even miss out the start and stop indices
print(animals[::2])

What does the code snippet do, and what is its output? - (2)

A

The code slices animals from the beginning to the end of the list in steps of 2, effectively extracting every other item from the list.

It prints the result: [‘ant’, ‘cat’, ‘elk’, ‘goose’].

61
Q

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

And we can use any step we like, including negative numbers
print(animals[::-1]) # printing animals in reverse order

Describe the output of the given code snippet.

A

The code prints animals list in reverse order by slicing it with a step of -1: [‘horse’, ‘goose’, ‘frog’, ‘elk’, ‘deer’, ‘cat’, ‘bear’, ‘ant’].

62
Q

Describe what the given code snippet does - (2)

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], same output, or write in reverse do ‘[::-1]’
print(numbers_requested)

A

The code extracts every third number from the list my_special_number, starting with the first number, and prints the result: [‘1’, ‘7’, ‘3’].

my_special_number can be written as as [0::3] or [::3],

63
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.

my_special_number=[‘1’,’5’,’2’,’7’,’9’,’2’,’3’,’8’,’8’]
numbers_requested=my_special_number[xxxxx]
print(numbers_requested)

A

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], same output,
print(numbers_requested)

64
Q

As well as adding elements, we may wish to

A

remove element from the list.

65
Q

What are the two main ways of removing elements of a list? - (2)

A
  1. Pop
  2. Del statement
66
Q

Explain the functionality of the .pop() method when removing items from a list - (2)

A

The .pop() method in Python removes and returns the element at the specified index from a list.

It modifies the original list by removing the element and optionally allows you to storing the removed element in another variable.

67
Q

Describe the purpose of the del statement when removing items from a list - (2)

A

The del statement in Python is used to remove an item or slice from a list by specifying its index.

It directly modifies the original list by deleting the specified item, and it does not return the removed item as .pop() does.

68
Q

Describe what the given code snippet does using the .pop() method - (3)

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

print(my_list)

thing_removed = my_list.pop(2) #stores thing deleted which is 30
print(thing_removed) # prints out 30

print(my_list) # prints out list with ‘30’ deleted

A

The code removes the element at index 2 from the list my_list using the .pop() method.

It stores the removed element in the variable thing_removed which is ‘30’ and prints it.

Then, it prints the updated list (my_list) without the removed element ‘[10,20,40,50]’

69
Q

Describe what the given code snippet does using the del statement - (2)

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

del my_list[0] #or use del statement to delete first element of list ‘10’

print(my_list) #prints new list with 10 removed

A

The code uses the del statement to remove the element at index 0 from the list my_list, which is ‘10’.

It then prints the updated list of my_list without the removed element: ‘[20,30,40,50]’

70
Q

Question: Explain the functionality of the sorted function when sorting a list - (2)

A

The sorted function in Python returns a new list containing the elements of the original list sorted in ascending order.

It does not modify the original list, instead, it creates a new sorted list.

71
Q

Describe the purpose of the .sort() method when sorting a list.

A

he .sort() method in Python sorts the elements of a list in ascending order in-place, meaning it directly modifies the original list.

It does not return a new list but instead sorts the elements within the original list itself.

72
Q

What are the main differences between the sorted function and the .sort() method in Python? - (2)

A

The main difference between sorted and .sort() is that sorted returns a new sorted list without modifying the original list, while .sort() sorts the original list in-place, directly modifying it.

Additionally, sorted can be used with any iterable (e.g., lists, tuples, strings, dictionaries etc…), while .sort() can only be used with lists.

73
Q

Describe what the given code snippet does using the sorted function - (3)

my_num_list = [50, 40, 10, 20]
my_sorted_list = sorted(my_num_list)

print(my_sorted_list)
print(my_num_list)

A

The code snippet sorts the list my_num_list using the sorted function and stores the sorted result in the variable my_sorted_list which is [10,20,40,50]

It then prints both the sorted list of [10,20,40,50] and the original list [50,40,10,20]

The original list remains unchanged after sorting.

74
Q

Describe what the given code snippet does using the .sort() method - (3)

my_num_list = [50, 40, 10, 20]
my_num_list.sort()
print(my_num_list)

A

The code snippet sorts the list my_num_list in-place using the .sort() method which is [10,20,40,50]

It directly modifies the original list, sorting it in ascending order.

Then, it prints the sorted list which is [10,20,40,50]

75
Q

What is another difference between sorted and .sort()? - (4)

A

sorted() is a built-in Python function, which means it’s a function that’s part of the Python language itself.

You can call it directly without needing an object instance.

On the other hand, .sort() is a method of the list class in Python. It’s called a “member function” or “method” because it’s associated with objects of the list type.

You call it on a list object using dot notation, like my_list.sort(),

76
Q

If we want to sort the array in place i.e., change the current variable we can use the

A

.sort member function

77
Q

What is the purpose of the .count() method when working with lists? - (3)

A

The .count() method in Python is used to count the number of occurrences of a specific element within a list.

It returns the count of occurrences of the specified element in the list

The argument you provide to the .count() method is the element you want to count occurrences of within the list.

78
Q

Fix the code:

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.

Hint: Start by making a list of 15 numbers between 0 and 5
my_list=[0,2,4, …..]
# Then print out the list
print(my_list)
my_list.sort()
print(my_list)

Then count how many elements in the list are set to 0, 1 , 2 etc…
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))

A

my_list = [3, 1, 4, 0, 2, 5, 3, 2, 1, 0, 4, 5, 3, 2, 1]

Print out the original list
print(“Original list:”, my_list)

Sort the list
my_list.sort()

Print the sorted list
print(“Sorted list:”, my_list)

79
Q

What is the output of the given code snippet? - (4)

Storing and sorting scores

Make a list of 15 numbers between 0 and 5
my_list = [3, 1, 4, 0, 2, 5, 3, 2, 1, 0, 4, 5, 3, 2, 1]

Print out the original list
print(“Original list:”, my_list)

Sort the list
my_list.sort()

Print the sorted list
print(“Sorted list:”, my_list)

A

The output will display the original list of scores, followed by the sorted list of scores in ascending order.

Output:
Original list: [3, 1, 4, 0, 2, 5, 3, 2, 1, 0, 4, 5, 3, 2, 1]
Sorted list: [0, 0, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 4, 4, 5]

80
Q

How would you define a tuple? - (2)

A

A tuple is an ordered collection of elements, similar to a list.

However, tuples are immutable, meaning their contents cannot be changed after creation.

81
Q

What are the similarities and differences between tuples and lists? - (4)

A

Both tuples and lists can store multiple elements and can be indexed and sliced.

However, tuples are immutable meaning you can’t add or remove items to/from a tuple, while lists are mutable.

Tuples are typically used for fixed collections of data, while lists are used for collections that may need to be modified.

Differences between tuples and lists are tuples are defined using ‘()’ whereas lists use ‘[]’

82
Q

We can create an empty tule using

A

round brackets ‘()’

83
Q

What is the output of the given code snippet? - (4)

a = ()

Printing the type and content of the tuple
print(type(a))
print(a)

A

The output will display the type of the variable a, which is tuple, and an empty tuple ().

<class ‘tuple’>
()

84
Q

The problem with creating an empty tuple is that

A

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

85
Q

More commonly, we would create a tuple with

A

existing content:

86
Q

What is the output of the given code snippet?

Creating a tuple with existing content
a = (1, 2, 3)

Printing the tuple
print(a)

A

The output will display the tuple (1, 2, 3) containing the numbers 1, 2, and 3.

87
Q

With tuples you can perform tuple operations like - (2)

A

extract items from tuple e.g., my_tuple[1]

and count length of type using len()

88
Q

What is the output of this code below?

Accessing an item in a tuple and getting its length
my_tuple = (5, 10, 15)

print(my_tuple[1]) # Accessing the second item in the tuple
print(len(my_tuple)) # Getting the length of the tuple

A

10
3

89
Q

What happens when you attempt to modify an item in a tuple?

A

Modifying an item in a tuple will raise a TypeError exception since tuples are immutable and do not support item assignment.

90
Q

What is output of this code?

Attempting to modify an item in a tuple (will raise a TypeError exception)
my_tuple = (5, 10, 15)

my_tuple[0] = 100 # This will raise a TypeError exception

A

TypeError: ‘tuple’ object does not support item assignment

91
Q

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

A

(turn it into) a list and back again.

92
Q

if you have a tuple which you need to modify, you can cast it to (turn it into) a list and back again. This does not modify

A

the first tuple, but creates a new one with new content:

93
Q

What is output of this code?

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

(1, 2, 3, 4)
(100, 2, 3, 4)

94
Q

What does the provided code snippet do? - (2)

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

The code snippet converts the original tuple my_orig_tuple into a list my_tmp_list, modifies the first element of the list to 100, and then converts the modified list back into a tuple my_new_tuple.

It finally prints both the original and modified tuples.

95
Q

What is the purpose of loops in programming?

A

Loops in programming are used to automate repetitive tasks, making coding more efficient and reducing manual effort

96
Q

Examples of using lops to repeat simple operations that would be useful like

A

making lots of stimuli for an experiment or analyzing lots of different datasets.

97
Q

What is a general structure of for loop?

A
98
Q

Explain general structure of for loop - (4)

A

LOOPVARIABLE (which can be named whatever you want) will be set to the first item in LIST_OF_THINGS_TO_ITERATE_OVER.

The code which is indented (just a comment in this case) will then run.

Once all of the code which is indented has been run, the loop will go back to the top, LOOPVARIABLE will be set to the second item in LIST_OF_THINGS_TO_ITERATE_OVER and all of the indented code will run again.

This will repeat for each element in LIST_OF_THINGS_TO_ITERATE_OVER.

99
Q

Describe this code -(4)

for t in [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]:
print(“Hello!”)
print(“Hello”,t)

A

In the given code snippet, the for loop iterates over each element in the list [1, 2, 3, 4, 5, 6, 7, 8, 9, 10].

During each iteration, the loop variable ‘t’ takes on the value of the current element in the list.

Within the loop, the first print statement prints “Hello!” for each iteration, resulting in the message being printed 10 times.

The second print statement includes the value of ‘t’, causing “Hello” to be printed along with the current value of ‘t’ for each iteration, producing output where “Hello” is printed 10 times followed by “Hello” and the numbers 1 through 10 respectively.

100
Q

What is the output of this code?

for t in [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]:
print(“Hello!”)
print(“Hello”,t)

A

Hello!
Hello 1
Hello!
Hello 2
Hello!
Hello 3
Hello!
Hello 4
Hello!
Hello 5
Hello!
Hello 6
Hello!
Hello 7
Hello!
Hello 8
Hello!
Hello 9
Hello!
Hello 10

101
Q

What is structure of for loop in Python? - (3)

A

The for keyword starts the loop. It is followed by the variable which is created to run the loop.

The keyword in is then used, followed by the expression which gives the list of items over which to iterate.

Finally, there is a colon : which shows that the loop is starting.

102
Q
A
103
Q

In the for loop

The for keyword…

It is followed by…

The keyword in…

Finaly there is :

The code inside te for loop is … - (6)

A

The for keyword starts the loop.

It is followed by the variable which is created to run the loop.

The keyword in is then used, followed by the expression which gives the list of items over which to iterate.

As we will see later, this is not always a list or tuple - there are other possibilities.

Finally, there is a colon : which shows that the loop is starting.

The code inside the loop is indented. In other words it is shifted to the right - like this line

104
Q

In loops, Python works out where your loop ends by - (2)

A

looking at the indentation of the text – i.e. it uses spaces. At first this can be confusing but it becomes second nature after a while.

105
Q

To ident code inside loop you can either use

A

4 spaces or tab

106
Q

Create a for loop that produces 1-10

A
107
Q

Iterating over a list refers to the process of

A

accessing each element in the list one by one in a sequential manner.

108
Q

The simplest form of a loop involves

A

setting up a list and then performing some code for each entry in the list.

109
Q

The simplest form of a loop involves setting up a list and then performing some code for each entry in the list. For example, code below shows..

A

we print each element in a list followed by itself squared

110
Q

Output of this code and explain - (4):

A

Meaning:

print(x,x**2) is idented within for loop so we print each element in a list followed by itself squared:

In print(x.5) is not idented within for loop and identation is different from print(x,x2) so left the for loop

print(x,x**.5) square root the last element of the list (‘x’) which is 40 and prints “Done”

Output:
10 100
20 400
30 900
40 1600
6.324555320336759
Done

111
Q

Example of for loop written out in detail/full

A
112
Q

For loops do not have to be on a single line as we can write:

A
113
Q

Explain this code and give its output:

A

Meaning:
The loop iterates over each element in the list my_list.

For each iteration, it prints “Hello”.

It computes the square of the current element (x) and stores it in y.

It then prints both the current element (x) and its square (y).

Output:
Hello
10 100
Hello
20 400
Hello
30 900
Hello
40 1600

114
Q

Long-handed version of the for loop code

A
115
Q

You can run any code you want inside of a loop. One thing which you should not do however, is to - (2)

A

delete an item in a list whilst you are looping over the list.

This will cause hard to find problems in your code and almost certainly not do what you want

116
Q

Write a code that has a list 10-100 stored in my_list = [] var

For loop that loops over that list and prints out value of x and its x squared and its square root on each iteration

A
117
Q

What is output of the code?

A
118
Q

What is nested for loops? - (3)

A

situation where one for loop is contained within another for loop.

This means that one loop runs inside another loop.

Each time the outer loop runs once, the inner loop can potentially run multiple times, depending on its own iteration behavior.

119
Q

For nested for loops it is

A

important to follow the indentation carefully reading this code.

120
Q

Meaning of this nested for loop example - (13)

A

As we can see, the first loop uses x as its loop variable.

On line 4, this will initially be set to the first value of my_first_list which is 1 (this is represented by x = 1 in the output comments).

We then progress to line 5 where we print out the statement Before Y loop starts.

On line 7, another loop is constructed.

The second loop uses y as its loop variable.

You should always use a different loop variable for each nested loop.

At this point, y will be set to the first value in my_second_list, which is 50 (this is represented by # y = 50 in the output comments).

We then execute the code within the loop on line 8 (the print function call) which prints out the values of both x and y.

At this point, we run out of code, so we go back to the innermost loop (line 7) and update y to 60.

We run the print again, then update y to 70 and run the print again.

We have now finished the “inner” y loop and execute line 10 which prints out the string After Y loop ends.

We then go back to line 4 and update the x variable to 2.

We now continue to line 5 again, which causes us to go print the Before Y loop starts string and then go around the y loop again, making y equal to 50, 60, and 70 in turn in the same way that we did previously

121
Q

Long-handed version of this for loop

A
122
Q

Fix the code to simulate all possible sums of two 6-sided dice, Which number is the most common? - (2)

A

It determines which number is the most common by printing the sum of each pair of throws and then analyzing the results.

The most common number should be 7 since there are more combinations of dice throws that sum to 7 than any other number

123
Q

What is range() in Python? - (2)

A

built-in function used to generate a sequence of numbers.

It’s commonly used in loops to iterate over a specific range of numbers.

124
Q

3 ways to use/call range() function - (3)

A
  1. range(stop)
  2. range(start,stop)
  3. range(start,stop,setp)
125
Q

What is range(stop)

A

This generates a sequence of numbers starting from 0 up to (but not including) the specified stop value.

126
Q

What is range(start,stop)?

A

This generates a sequence of numbers starting from start up to (but not including) the stop value.

127
Q

What is range(start,stop,step) - (2)

A

This generates a sequence of numbers starting from start up to (but not including) the stop value, with a specified step size between each number.

The step parameter is optional and defaults to 1 if not provided

128
Q

In python, all stop-style parameters are exclusive; i.e. - (3)

A

they are not included in the list which is returned.

This means that if we ask for range(0, 4), we will get the numbers 0, 1, 2, 3.

Forgetting how this works is a common source of bugs.

129
Q

What will this output give you?

x = range(5)
print(type(x))
print(x)

A

<class ‘range’>
range(0, 5)
print the generator

130
Q

What will this code give you?

x = list(range(5))
print(type(x))
print(x)

0 it is convert to list and print

A

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

131
Q

What will this code give you?

x = list(range(1, 500))
print(x)

A

[1, 2, 3, 4, 5, …., 499]

132
Q

The step parameter in range… - (2)

A

sets the increment or decrement.

Setting this to be negative lets us count backwards.

133
Q

What will these code give? - (3)

A

[1, 3]
[5, 4, 3, 2, 1]
[4, 3, 2, 1, 0]

134
Q

range function generates a sequence of integer numbers within a specified range.

If you want to use floating point numbers then

A

use the arange function from the numpy module – we will cover this in a future session.

135
Q

Exercise:
Write python code, using a loop, to count between -10 and 10 (inclusive) and for each number print out the number and its cube (i.e. the number to the power 3).

A