Creative Programming
Spring 2025
CUL1122 Lecture #09
Python Lists
for Solving Optimization Problems
Today
❖Lists and Definite Loops
❖Enumerating List Items
❖Adding and Removing List Items
❖Checking for Presence, Quantity, and Index of Specific Items
❖List Slicing
3
Python Lists
❖A list is a collection of data enclosed within square brackets ([]) and
separated by commas.
❖Lists are used to store multiple items in a single variable.
❖List items can be of any data type:
4
List Items
❖1) Ordered: List items maintain a consistent sequence.
▪ They are indexed, starting with the first item at index [0], the second at index
[1], and so on.
▪ To access list items, simply refer to their index numbers.
5
List Items
❖2) Changeable: Lists are flexible because you can edit, add, or remove
items even after they are created.
▪ When you append new items to a list, they are added to the end.
▪ To modify a specific list item, assign a new value to its index.
6
List Items
❖3) Allowing Duplicates: Since lists are indexed, they can contain
duplicate values, with each occupying a unique position.
7
Counting Items in a List
❖The len() function takes a list as an argument and returns the number
of elements in that list.
❖In fact, len() can be used to determine the number of elements in any
iterable collection, including strings.
8
Using the range() Function
❖The range() function generates a sequence of numbers starting from
zero and ending at one less than the specified parameter.
❖You can construct an index loop using a for statement in conjunction
with an integer iterator.
9
Enumerating List Items #1: Using for Loop with range()
❖To access each item in a list using range(len(list)), you can utilize a for
loop.
❖The loop variable, acting as an index, iterates over the range of indices
corresponding to the length of the list.
❖Let’s explore how to use a for loop with range(len(list)) to access each
item in a given list.
▪ 1) Iterating through the indices: The range(len(list)) function generates a
sequence of indices that correspond to the length of the provided list.
for index in range(len(list)):
print(list[index])
10
Enumerating List Items #1: Using for Loop with range()
▪ 2) Using the index to access list elements: Within each iteration of the loop, the
loop variable—typically denoted as ‘index’—represents the index of the current
element being accessed in the list.
➢You can use this index to retrieve each item from the list.
▪ 3) Performing operations on list elements: Inside the loop block, you can use
the index variable to access list elements and perform operations on them.
11
Enumerating List Items #2: Using enumerate()
❖The enumerate() function in Python accepts a sequence as input and
produces an enumerate object.
▪ This object is structured as key-value pairs, where the key represents the index
of each item and the value represents the item itself.
❖The syntax for enumerate() is as follows: enumerate(iterable, start=0).
Parameter Required Description Default
iterable Required A sequence like a list, tuple or iterator N/A
start Optional The starting index for the enumerate object 0
12
Enumerating List Items #2: Using enumerate()
❖To access list items using the enumerate() function:
▪ 1) Use the enumerate() function with the list as the argument.
▪ 2) Iterate through the resulting enumerate object in a for loop.
▪ 3) Each iteration provides both the index and the corresponding list item.
13
Adding Items to a List
❖1) Utilizing the append() Method
▪ The append() method facilitates the addition
of items to the end of a list.
❖2) Employing the insert() Method
▪ To add items at a specific position, the insert()
method is utilized.
14
Removing Items from a List
❖1) Employing the remove() Method
▪ The remove() method eliminates the first
occurrence of the specified item from the list.
▪ If the item does not exist, it raises a ValueError.
❖2) Utilizing the pop() Method
▪ The pop() method is another option for
removing and returning an item from the list.
▪ By default, it removes the last item in the list.
15
Checking for the Presence of a Specific Item
❖Python includes two membership operators, in and not in, which
enable you to determine whether an item is present in a list.
❖These operators return either True or False, based on the presence or
absence of the item in the list.
16
Checking the Quantity of a Specific Item
❖The count() method accepts a value as input and returns the number of
occurrences of that value in the list.
❖The syntax for count() is as follows: list.count(value).
Parameter Required Description Default
value Required The value to search for N/A
❖Similarly, the count(value, start, end) for strings returns the number of
times a value appears within the specified range of the given string.
Parameter Required Description Default
value Required The string to value to search for N/A
start Optional The position to start the search 0
end Optional The position to end the search End of the string
17
Checking the Quantity of a Specific Item
❖Counting the number of times values appear in a list and string:
18
Finding the Index of a Specific Item
❖The index() method allows you to determine the index of a given item
within a list.
▪ In cases where duplicate items exist, it returns the index of the first occurrence
of the specified item.
▪ If the item is not found in the list, the method raises a ValueError.
❖The syntax for index() is as follows: list.index(item, start, end).
Parameter Required Description Default
item Required The item that you want to get the index N/A
start Optional The index to start the search 0
end Optional The index to end the search The end of the list
19
Finding the Index of a Specific Item
❖The index() method returns the index of the specified item in the list.
❖You can restrict the search by specifying the start and end indices.
20
List Slicing in Python
❖In Python, list slicing enables you to extract a portion of a list by
specifying start and end indices.
▪ To slice elements within a range defined by start_index and end_index
(exclusive), you can use the syntax [start_index:end_index].
❖Positive indices are used to access elements from the start of the list,
beginning at index 0 and increasing from left to right.
❖Conversely, negative indices allow access to elements from the end of
the list, starting from -1 and decreasing from right to left.
Positive Indexes 0 1 2 3 4 5
Items Popcorn Soda Pretzels Ice Cream Cookies Nachos
Negative Indexes -6 -5 -4 -3 -2 -1
21
List Slicing in Python
❖List slicing generates a new list containing the selected elements:
▪ 1) Slicing items from index 1 to 3 (index 3 is exclusive): list[1:3]
▪ 2) Slicing items from the beginning to index 3 (index 4 is exclusive): list[:4]
▪ 3) Slicing items from index 3 to the end: list[3:]
▪ 4) Slicing the entire list (creates a copy): list[:]
22
Lab 9
Today
❖1) Listing Items in a List
❖2) Finding the Index of a Specific Item in a List
❖3) Calculating Manual Statistics
❖4) Verifying Palindromes
24
Exercise #1: Listing Items in a List
❖Create a script that enumerates Netflix Korean dramas from the year
2023 using the range() as well as enumerate() functions.
▪ First, use range(len(list)) to generate a range for accessing each item.
▪ Then, use the enumerate() function to produce an enumerate object for
accessing each item.
25
Exercise #2: Finding the Index of a Specific Item in a List
❖Create a script to locate dramas based on their genres and display their
titles and number of episodes if found.
▪ Set up lists as follows:
➢drama_titles = [‘The Glory’, ‘Queenmaker’, ‘Black Knight’, ‘D.P. 2’, ‘Mask Girl’]
➢drama_genres = [‘Crime’, ‘Drama’, ‘SF’, ‘Military’, ‘Thriller’]
➢drama_num_episodes = [16, 11, 6, 6, 7]
▪ Search for dramas in the genres of ‘SF’ and ‘Comedy’.
26
Exercise #3: Calculating Manual Statistics
❖Create a script that calculates the maximum and average values from a
list of integers.
▪ Write two functions to find the maximum and average of a list of integers.
▪ Ask the user for a start and end value, then create a list of integers in that range.
▪ Use your functions to calculate and display the results.
27
Exercise #4: Verifying Palindromes
❖A palindrome is a word, phrase, or
sentence that reads the same forward
and backward.
❖‘Able was I, ere I saw Elba.’– attributed
to Napoleon
❖‘Are we not drawn onward, we few,
drawn onward to new era?’– attributed
to Anne Michaels
28
Exercise #4: Verifying Palindromes
❖Create a script that determines whether a given string is a palindrome,
regardless of language.
▪ 1) Begin by converting the original string to lowercase to ensure case
insensitivity, and accept only alphanumeric characters.
➢For example, ‘A Santa at NASA.’ becomes ‘a santa at nasa.’ and then ‘asantatnasa’.
29
Exercise #4: Verifying Palindromes
▪ Create a reversed version of the string and compare characters at each index
throughout the length of the string.
Index 0 1 2 3 4 5 6 7 8 9 10 11
Original String a s a n t a a t n a s a
Reversed String a s a n t a a t n a s a
30
수고하셨습니다!
31