You are on page 1of 5

Week 8 Unit 3 (Lists and Loops)

LISTS

 Lists is also known as “Arrays”


 Lists is a data structure in Python that is a mutable (can change the item
inside) , ordered sequence (index location) of elements.

Lists and Loops 



1st element in a lists always located at index 0
The element inside of a lists is called an item
 Lists have different data types between square brackets [ ]
 Lists is also known as Data Collection (data types that can store multiple
items)

27 28 By: JMI

LISTS LISTS

 Declaring a Lists of Numbers  Declaring a List of Mixed Data Types

sample code: Output: sample code: Output:


lists = [5, 10, 15.2, 20] [5, 10, 15.2, 20] num = 4.3 [4.3, “word”, True]
print(lists) Note: it includes bracket data = [num, "word", True] # the power of data collection
print(data)

 Accessing Elements Within a List


 Lists Within Lists
sample code: sample code:
data = [5, "book", [ 34, "hello" ], True] # lists can hold any type
lists = [5, 10, 15.2, 20]
print(data)
print( lists[1] ) # will output the value at index 1 = 10
num = lists[2] # saves index value 2 into num print( data[2] )
print(num) # prints value assigned to num Output:
Output: [5, ‘book’, [34, ‘hello’], True]
10 and 15.2 [34, ‘hello’]

29 By: JMI 30 By: JMI

ECE 106 - Computer Programming


Prepared by: Engr. Jeanne M. Imbuido 1
Week 8 Unit 3 (Lists and Loops)

LISTS LISTS

 Accessing Lists Within Lists  Changing Values in a List


sample code: using double bracket notation to access lists within lists
data = [5, "book", [ 34, "hello" ], True] sample code: changing values in a list through index
print( data[2][0] ) # will output 34
inner_list = data[2] # inner list will equal [34, 'hello'] data = [5, 10, 15, 20]
print( inner_list[1] ) # will output 'hello‘ print(data)
Output: data[0] = 100 # change the value at index 0 - (5 to 100)
34 print(data)
Hello
Output:
[5, 10,15, 20] # value before altering at index 0
[100, 10, 15, 20] # changed index 0 value to 100

print( data[ 1 ][ 0 ] ) # will output 'b'


31 By: JMI 32 By: JMI

LISTS LISTS

 ADDING ITEMS TO YOUR LISTS  Working with Numerical List Data


- Python has 2 different methods, by using .append( ) or .insert( ) function - Python provides a few functions for us to use on lists of numerical data, such as
min, max, and sum which are frequently used.
sample code: output:
nums = [10, 20] [10, 20, 5] sample code:
nums.append(5) # using min, max, and sum
print(nums) note: 5 is added to the back lists nums = [5, 3, 9]
print( min(nums) ) # will find the lowest number in the list which is 3
Sample code: output: print( max(nums) ) # will find the highest number in the list which is 9
words = [ "ball", "base" ] [‘glove’, ‘ball’, ‘base’] print( sum(nums) ) # will add all numbers in the list & return the sum which is 17
words.insert(0, "glove") # first number is the index, second is the value
print(words)  Sorting a List
- Python provides 2 different method, sorted ( ) will change the original list , while
note: Glove is in the 0 index now because we specified that index within our insert
.sort ( ) returns a copy.
method.

33 By: JMI 34 By: JMI

ECE 106 - Computer Programming


Prepared by: Engr. Jeanne M. Imbuido 2
Week 8 Unit 3 (Lists and Loops)

LISTS LISTS

sample code:  Conditionals and Lists


# using sorted on lists for numerical and alphabetical data sample code:
nums = [5, 8, 0, 2] # using conditional statement keywords “in” and “not in” on a list
sorted_nums = sorted(nums) # save to a new variable to use later
print(nums, sorted_nums) # the original list is in tact names = [ "Jack", "Robert", "Mary" ]
if "Mary" in names:
sample code:
print("found") # will run since Mary is in the list
# sorting a list with .sort() in-place
if "Jimmy" not in names:
nums = [5, 0, 8, 3]
print("not found") # will run since Jimmy is not in the list
nums.sort( ) # alters the original variable directly
print(nums) sample code:
# using conditionals to see if a list is empty

nums = [ ]
if not nums: # could also say 'if nums == []'
print("empty")
35 By: JMI 36 By: JMI

LOOPS LOOPS
sample code:
 ability to run the same code more than once without writing the same lines of code several times
# writing your first for loop using range
 Loops will always run until a condition is met.
for num in range(5):
print( f"Value: {num}")

 This loop is essentially counting to five and printing out each number, begins at 0 by default and
assign to temporary variable num
 Each time through the loop is what we call an iteration.

 above syntax suggests that the loop will run five times.
 Every for loop begins with the keyword “for”. Then you define a temporary variable, sometimes
known as a counter or index.
 Next is the “in” keyword, followed by the range ( ) function
 Lastly, we have a colon : , to end the statement.
 All for loops will follow this exact structure of keyword, variable, keyword, function, and colon.
37 By: JMI 38 By: JMI

ECE 106 - Computer Programming


Prepared by: Engr. Jeanne M. Imbuido 3
Week 8 Unit 3 (Lists and Loops)

LOOPS LOOPS

Range ( ) Looping by Element


 allows us to count from one number to another while being able to define where to start  When working with data types that are iterable, meaning they have a collection of elements that can
and end and how much we increment or decrement by. Meaning that we could count be looped over.
every other number or every fifth number if we wanted to. sample code:
# printing all characters in a name using the 'in' keyword
 When used with a for loop, it gives us the ability to loop a certain number of times.
name = "John Smith"
sample code: for letter in name:
# providing the start, stop, and step for the range function print(f"Value: {letter}")
output:
for num in range(2, 10, 2):
print(f"Value: {num}") # will print all evens between 2 and 10
output:
Value: 2
Value: 4
Value: 6
Value: 8
39 By: JMI 40 By: JMI

LOOPS WHILE LOOPS

Continue Statement  A while loop is generally used when you need to loop based on a condition rather than counting.
 Once a continue statement is hit, the current iteration stops and goes back to the top of the loop.. Writing a “while” Loop
sample code: output:  It allows us to break out of a loop at any point in time.
# using the continue statement within a foor loop 0
sample code:
for num in range(5): 1
# writing your first while loop
if num == 3: 2
health = 10
continue 4
while health > 0:
print(num) print(health)
Break Statement health -= 1 # forgetting this line will result in infinite loop
Output:
 It allows us to break out of a loop at any point in time.
 This will continue to print out the value of health until the condition is met. In this case, once health is no longer
sample code: output: greater than zero, the loop stops running. On the last line, we decrement health by one, so each iteration reduces
#breaking out of a loop using the 'break' keyword 0
health closer to zero.
for num in range(5): 1
if num == 3: 2  If we didn’t decrement health at any point in time, this would become an infinite loop (which is bad).
break for loops are generally used when you need to count or iterate over a collection of elements.
print(num) while loops are generally used when doing condition-based looping.
41 By: JMI 42 By: JMI

ECE 106 - Computer Programming


Prepared by: Engr. Jeanne M. Imbuido 4
Week 8 Unit 3 (Lists and Loops)

LOOPS and LISTS

Using for Loops in a Lists


 When iterating over a list with a for loop, the syntax looks like when we used the range function
previously but this time we use a temporary variable, the in keyword, and the name of the list.
sample code:
# using a for loop to print all items in a list
sports = [ "Baseball", "Hockey", "Football", "Basketball" ]
for sport in sports:
print(sport)

Using while Loops in a Lists


 While loops are always used for conditional looping. One great use case for a while loop with lists is
removing an item, but you still can use it in other instances:
sample code:
# using the while loop to remove a certain value
names = [ "Bob", "Jack", "Rob", "Bob", "Robert" ]
while "Bob" in names:
names.remove("Bob") # removes all instances of 'Bob'
print(names)
43 By: JMI

ECE 106 - Computer Programming


Prepared by: Engr. Jeanne M. Imbuido 5

You might also like