3.3 - Boolean Values, Conditional Execution, Loops, Lists & List Processing, Logical & Bitwise Operations (PCEP-30)

Ace your homework & exams now with Quizwiz!

example comments; the i variable takes the values 0, 1, 2, 3, and 4, and then it indexes the list, selecting the subsequent elements: the first, second, third, fourth and fifth;

each of these elements is added together by the += operator to the total variable, giving the final result at the end of the loop;

**key takeaways; end

end

"List comprehension" allows you to create new lists from existing ones; in a concise and elegant way. The syntax of a list comprehension looks as follows [expression for element in list if conditional]

for element in list: if conditional: expression

example 3; swapping values in lists using 'for loop' my_list = [10, 1, 8, 3, 5] length = len(my_list)

for i in range(length // 2): my_list[i], my_list[length - i - 1] = my_list[length-i-1], my_list[i] print(my_list) [5, 3, 8, 1, 10]

Similarly, if you omit the end in your slice, it is assumed that you want the slice to end at the element with the index; len(my_list)

len(my_list)

There is also a list method called reverse(), which you can use to reverse the list (flip for example)

lst = [5, 3, 1, 2, 4] print(lst) lst.reverse() print(lst) # outputs: [4, 2, 1, 3, 5]

You can use the sort() method to sort elements of a list (flip for example)

lst = [5, 3, 1, 2, 4] print(lst) lst.sort() print(lst) # outputs: [1, 2, 3, 4, 5]

You can test if some items exist in a list or not using the keywords "in" and "not in" (flip card)

my_list = ["A", "B", 1, 2] print("A" in my_list) # outputs: True print("C" not in my_list) # outputs: True print(2 not in my_list) # outputs: False

The len() function may be used to check the list's length (flip for example)

my_list = ["white", "purple", "blue", "yellow", "green"] print(len(my_list)) output: 5

Lists can be iterated through using the "for" loop (flip for example)

my_list = ["white", "purple", "blue", "yellow", "green"] for color in my_list: *print(color) (output: white. purple, blue, yellow, green **all on separate lines)

You can delete slices using the "del" instruction (flip card)

my_list = [1, 2, 3, 4, 5] del my_list[0:2] print(my_list) # outputs: [3, 4, 5] del my_list[:] print(my_list) # deletes the list content, outputs: []

The start and end parameters are optional when performing a slice: list[start:end] When you have a integer in 'end', that spot is not include in the slice, however if it's blank (in the end spot), it's include because you are going off of the length of the list (flip card)

my_list = [1, 2, 3, 4, 5] slice_one = my_list[2: ] slice_two = my_list[ :2] slice_three = my_list[-2: ] print(slice_one) # outputs: [3, 4, 5] print(slice_two) # outputs: [1, 2] print(slice_three) # outputs: [4, 5]

list elements can be deleted (flip for example)

my_list = [1, 2, 3, 4] del my_list[2] print(my_list) # outputs: [1, 2, 4] del my_list # deletes the whole list

The "list" is a type of data in Python used to store multiple objects. It is an ordered and mutable collection of comma-separated items between square brackets

my_list = [1, None, True, "I am a string", 256, 0]

if you want python to sort your list in 'ascending order', do the following (flip card)

my_list = [8, 10, 6, 2, 4] my_list.sort() print(my_list) output: [2, 4, 6, 8, 10]

how do you update indices within a list?

my_list [1] = $ would update element 2, with $

list sorting; how do you sort a variable in ascending order? use the variable my_list (my_list.sort())

my_list.sort() you would then print the results

example 2; swapping values in lists my_list = [10,1,8,3,5]

my_list[0], my_list[4] = my_list[4], my_list[0] my_list[1], my_list[3] = my_list[3], my_list[1] [5, 3, 8, 1, 10]

If you omit the start in your slice, it is assumed that you want to get a slice beginning at the element with index 0; what are 2 ways to represent this?

my_list[:end] my_list[0:end]

if end is omitted in slice; what are 2 ways you can type this out in python? (

my_list[start: ] my_list[start : len(my_list)]

lists can be ________ (nested)

nested; brackets inside of brackets

example; 'in' operator, lists my_list = [0, 3, 12, 8, 2] print(5 in my_list)

output False; 5 isn't in the list

example; 'not in' operator, lists my_list = [0, 3, 12, 8, 2] print(5 not in my_list)

output True; 5 isn't in the list

slices; If the start specifies an element lying further than the one described by the end (from the list's beginning point of view), the slice will be empty

output would be the following []

a typical method invocation looks like this: result = data.method(arg)

result = data.method(arg)

A typical function invocation looks as follows: result = function(arg)

result = function(arg)

You can use 'negative' indices to perform slices, too. For example: (flip card)

sample_list = ["A", "B", "C", "D", "E"] new_list = sample_list[2:-1] print(new_list) # outputs: ['C', 'D']

section continued

section continued

A "slice" is an element of Python syntax that allows you to make a brand new copy of a list, or parts of a list. It actually "copies the list's contents", not the list's name.

slice; copies the list's contents

If you want to copy a list or part of the list, you can do it by performing __________ (slicing)

slicing

***start of the 'key takeaways'

start

**the key takeaways, start

start

in order to update, how is the indices arranged in a list? (starts with zero)

starts with zero

Lists; and many other complex Python entities; are "stored" in different ways than ordinary; scalar; variables

stored in a different way

slicing example; colors = ['red', 'green', 'orange'] copy_whole_colors = colors[:] # copy the entire list copy_part_colors = colors[0:2] # copy part of the list

the 'end' doesn't include the integer

if a list contains 'other variables', the output will display what? (the value of those variables)

the value of those variables

we've launched the for loop to run through its body length // 2 times

this works well for lists with both even and odd lengths, because when the list contains an odd number of elements, the middle one remains untouched

***end of key obj

true

**key takeaways (beginning)

true

If you have a list L1, then the following assignment: L2 = L1 does not make a copy of the L1 list, but makes the variables L1 and L2 point to one and the same list in memory

true

It looks fine with five elements. Will it still be acceptable with a list containing 100 elements? No, it won't. Can you use the for loop to do the same thing automatically, irrespective of the list's length? Yes, you can.

true

Lists can be indexed and updated

true

The for loop has a very special variant that can process lists very effectively - let's take a look at that

true

Using negative values for both start and end is possible (just like in indexing).

true

You can use 'nested lists' in Python to create "matrices" (i.e., two-dimensional lists)

true

adding elements to a list; You can start a list's life by making it empty, this is done with an empty pair of square brackets, and then adding new elements to it as needed

true

end is omitted in slice; the significance with the 'len(my_list)' the last index is included because the length of the list is more than the number of indices since the indices start at 0

true

how do you swap the values of two variables? you need the 2 variables you would like to swap; and a 3rd variable that serves as an auxiliary storage

true

lists; slices my_list[start:end] 'start' is the "index" of the 'first element included' in the slice; end is the "index" of the first element not included in the slice.

true

nested lists; lst = [1, [2, 3], 4] looks like if there is a nested list, the bracketed portion inside the list is its own index; where the length is 3 of the entire list

true

note the way in which the len() function has been employed - it makes the code independent of any possible changes in the list's content

true

the for instruction specifies the variable used to browse the list; i here; followed by the in keyword and the name of the list being processed; my_list here

true

the i variable is assigned the values of all the subsequent list's elements, and the process occurs as many times as there are elements in the list

true

the name of a list is the name of a "memory location where the list is stored"

true

the name of an ordinary variable is the "name of its content"

true

this means that you use the i variable as a copy of the elements' values, and you don't need to use indices

true

we've assigned the length variable with the current list's length, this makes our code a bit clearer and shorter

true

review; for loops if you have a range(2) how many times will the loop execute? (twice)

twice

how would this look in python if you want to swap values of 2 variables? (flip card) the output using the print function would be 2,1

variable_1 = 1 variable_2 = 2 variable_1, variable_2 = variable_2, variable_1

checks if a given element; its left argument; is currently stored somewhere inside the list; the right argument; - the operator returns True in this case.

'in' operator

checks if a given element; its left argument; is absent in a list - the operator returns True in this case. (not in operator)

'not in' operator

what two methods can you use to update a list? (append, insert)

- append (adds to the end of the list) - insert (puts value in specific spot, and shifts everything to right)

Python offers two very powerful operators, able to look through the list in order to check whether a specific value is stored inside the list or not. what are they? (in, not in)

- in - not in

my_list = [10, 1, 8, 3, 5] total = 0 for i in range(len(my_list)): *total += my_list[i] print(total)

27

my_list = [10,1,8,3,5] total = 0 for i in my_list: *total+=i print(total)

27

One of the most general forms of the slice looks as follows: my_list[start:end] (flip card)

As you can see, it resembles indexing, but the colon inside makes a big difference

example; slice (flip for output; [1]) list_1 = [1] list_2 = list_1[:] list_1[0] = 2 print(list_2)

Its output is [1]. [:] is able to produce a brand new list.

The previously described del instruction is able to delete more than just a list's element at once - it can delete slices too: my_list = [10, 8, 6, 4, 2] del my_list[1:3] print(my_list)

Note: in this case, the slice doesn't produce any new list! The snippet's output is: [10, 4, 2]

A slice of this form makes a new (target) list, taking elements from the source list - the elements of the indices from start to 'end - 1' (flip)

Note: not to end but to 'end - 1'. An element with an index equal to 'end' is the first element which does not take part in the slicing.

example list_1 = [1] list_2 = list_1 list_1[0] = 2 print(list_2) (output: [2]) (flip card)

The assignment: list_2 = list_1 copies the name of the array, not its contents. In effect, the two names (list_1 and list_2) identify the same location in the computer memory. Modifying one of them affects the other, and vice versa

Removing the slice from the code when deleting changes its meaning dramatically. my_list = [10, 8, 6, 4, 2] del my_list print(my_list)

The del instruction will delete the list itself, not its content. The print() function invocation from the last line of the code will then cause a runtime error

Deleting all the elements at once is possible too: my_list = [10, 8, 6, 4, 2] del my_list[:] print(my_list)

The list becomes empty, and the output is: []

example; 'slicing' my_list = [10, 8, 6, 4, 2] new_list = my_list[1:3] print(new_list)

The new_list list will have end - start (3 - 1 = 2) elements - the ones with "indices" equal to 1 and 2 (but not 3). The snippet's output is: [8, 6]

lists slices; with 'negative indices' my_list = [10, 8, 6, 4, 2] new_list = my_list[1:-1] print(new_list) (flip for output)

The snippet's output is: [8, 6, 4]

slices continued; As we've said before, omitting both start and end makes a copy of the whole list my_list = [10, 8, 6, 4, 2] new_list = my_list[:] print(new_list)

The snippet's output is: [10, 8, 6, 4, 2].

Note: we're not going to name it sum as Python uses the same name for one of its built-in functions - sum()

Using the same name would generally be considered a bad practice.

Let's assume that you want to calculate the sum of all the values stored in the my_list list.

You need a variable whose sum will be stored and initially assigned a value of 0 - its name will be total.

example - using append to add to list with for loop. What's the output using print? my_list = [] for i in range(5): *my_list.append(i + 1)

[1, 2, 3, 4, 5]

example my_list = [10, 8, 6, 4, 2] new_list = my_list[ :3] print(new_list)

[10,8,6]

What is the output of the following snippet? lst = [1, [2, 3], 4] print(lst[1]) print(len(lst))

[2, 3] 3

example my_list = [10, 8, 6, 4, 2] new_list = my_list[3 : len(my_list)] print(new_list)

[4, 2]

example - using insert to add to list with for loop. What's the output using print? my_list = [] for i in range(5): *my_list.insert(0, i + 1)

[5, 4, 3, 2, 1]

what is the demonstration of a 'slice' in python? ([:] colon surrounded by brackets)

[:] , colon surrounded by brackets

**key takeaways (beginninggg)

beginningggg

a sorting algorithm that compares two adjacent elements and swaps them until they are in the intended order (bubble sort)

bubble sort

Here's an example of a list comprehension ‒ the code creates a five-element list filled with the first five natural numbers raised to the power of 3:

cubed = [num ** 3 for num in range(5)] print(cubed) # outputs: [0, 1, 8, 27, 64]


Related study sets

NCLEX Cardiovascular Medication Questions (Saunders) ben

View Set

SPC Level 2 Exam 3- Heart Failure Adaptive Quiz

View Set

THE TRAGEDY OF JULIUS CAESAR BY WILLIAM SHAKESPEARE: ACT 3.1

View Set

Exam One other multiple choice question Chapter 1 to 8

View Set

Unit 7- Age Absolutism, Enlightenment, and Revolutions

View Set

Language, Thought, and Communication

View Set