Skip to content

kwaldenphd/python-lists-strings

Repository files navigation

Lists and Strings in Python

Creative Commons License This tutorial is licensed under a Creative Commons Attribution-NonCommercial 4.0 International License.

Lab Objectives

  • Practice utilizing lists and strings in the Python programming language
    • For strings, this includes creation, length and access, basic list operations, and basic method arguments
    • For lists, this includes creation, access, iteration, nesting, searching, concatenating, growing, deleting, sorting, and reversing
  • Understand and articulate the differences between lists and strings
  • Use Python methods and functions to work with strings and numbers
Panopto logo Lab overview
Panopto logo Lecture/live coding playlist

Acknowledgements

Elements of this lab procedure were adapted from materials developed by Dr. Peter Bui for the CSE 10101 "Elements of Computing I" course.

Elements of this lab procedure were adapted from materials developed by Dr. Janet Davis for the the CSC 105 "The Digital Age" course.

Elements of this lab procedure were adapted from materials developed by Dr. Corey Pennycuff for the CSE 10101 Elements of Computing (Fall 2019).

Elements of this lab procedure were adapted from materials developed by Lindsay K. Mattock for the the SLIS 5020 Computing Foundations course.

Table of Contents

Link to lab procedure as a Jupyter Notebook

Lecture and Live Coding

Throughout this lab, you will see a Panopto icon at the start of select sections.

This icon indicates there is lecture/live coding asynchronous content that accompanies this section of the lab.

You can click the link in the figure caption to access these materials (ND users only).

Example:

Panopto logo Lab overview
Panopto logo Lecture/live coding playlist

Lab Notebook Template

Lab notebook template:

Python Syntax: Methods and Functions

Panopto logo Lab overview
  1. Python has some specific terminology used to describe elements of code.

  2. Syntax: Programming languages have their own syntax, which are a set of rules that determine how programs (commands, lines of code) are written and interpreted. The language syntax includes both elements of the code visible to human readers as well as elements of the code executed by the machine.

  3. Function: We have a whole lab coming up on functions. For now, we can think of functions as a group of statements that perform a specific task. Python includes built-in functions like print(), dict(), input(), int(), and len(), but also allows you to create your own functions. Data, parameters, or arguments can be passed into a function, and a function can also return data.

  4. Parameters and arguments can be used interchangeably in Python.

  5. Method: In Python, a method is something that is applied to an object. That object could be a variable, string, number, or other type of data. A method is a function that is available for objects based on their type. For example append(), extend(), sort(), and reverse() are all methods that can be used with list object types. capitalize(), upper(), lower(), and title() are all methods that can be used with string object types.

  6. Function vs. Method: Functions are generic, while a method is called on an object. A method is associated with an object (and can access/interact with the data or information that is part of that object). Functions do not alter the state of an object, while a method can alter an object state.

Variables

  1. We worked with variables in our first Python lab. A variable is a placeholder for a piece of information. You can think of it as a basket or container.

  2. Python has a few rules for variables:

  • Variable names can only include letter, numbers, or underscores, but cannot start with a number.
  • Spaces are not permitted.
  • The names of Python methods and functions are reserved, meaning that they cannot be used as variable names. So, print cannot be used as a variable name.
  • As a rule, variable names should be short and descriptive.
Q1: In your own words, explain the difference between print(hello) and print(“hello”).

Strings

Panopto logo Strings
  1. What are strings?

  2. A string is a sequence of characters.

  3. Although we can have list of characters, often times we want to access and manipulate the sequence as an aggregate set of text rather than individual letters.

  4. Strings are identified by the “ ” or alternatively by ‘ ’.

# example that creates a new string variable
first_name = 'Katherine'

# check variable type
type(first_name)

# view value of first_name variable
first_name
# example that converts integer to string
str(10)

# example that converts float to string
str(15.0)

# example that converts boolean to string
str(True)
  1. Because certain operations on strings are so common, Python includes a variety of built-in methods that you can apply to a string object:

Title Methods

  1. Let's look at an example that uses different title methods.
# example using my name
name = "katherine walden"
  1. Next, we’ll use the print function with the method title. Python functions and methods always end with a (). Methods define an additional action that can be applied to the data.
# example using my name, printed in title case
name = "katherine walden"
print(name.title())
  1. Your program should output your data with a leading capital letter.

  2. We can also change the case using the upper() method and lower() method: print(name.upper()) outputs your string with all capital letters, while print(name.lower()) outputs your string in all lower case.

  • Katherine Walden
  • KATHERINE WALDEN
  • katherine walden
  1. Try adding two additional print() functions calling the name variable with each of these methods.
Q2: Describe the syntax of the three print statements generated in steps 14-18 in your own words. What is this code doing? Define the function and method for each example.
# Q2 examples
name = "katherine walden"
print(name.title())
print(name.upper())
print(name.lower())

Concatenation

  1. Let’s modify our code a bit and create two new variables first_name for your first name and last_name for your last name. We can then combine these two string variables (called concatenation) in a third variable called full_name.

  2. If we want our first and last name to be separated by a space, we need to tell Python to add one in by including the “ “, otherwise, each string will be printed back-to-back.

# assign string variables
first_name = "katherine"
last_name = "walden"

# use concatenation to create new variable
full_name = first_name + " " + last name

# output last variable
print(full_name)
  1. We can then use the print() function as we did before to output full_name in title case.
# assign string variables
first_name = "katherine"
last_name = "walden"

# use concatenation to create new variable
full_name = first_name + " " + last name

# output last variable in title case as part of print statement
print("Hello, " + full_name.title() + "!")
  1. We could combine strings and variables in the same print() function to output a full sentence to the screen.

  2. We could also assign this whole sentence to a variable and return the same output.

# assign string variables
first_name = "katherine"
last_name = "walden"

# use concatenation to create new variable
full_name = first_name + " " + last name

# use concatenation to create new variable
sentence="Hello, " + full_name.title() + "!"

# output last variable
print(sentence)
Q3: Explain how each of these programs (steps 20-23) work in your own words.
# step 20 program
# assign string variables
first_name = "katherine"
last_name = "walden"

# use concatenation to create new variable
full_name = first_name + " " + last name

# output last variable
print(full_name)
# step 21 program
# assign string variables
first_name = "katherine"
last_name = "walden"

# use concatenation to create new variable
full_name = first_name + " " + last name

# output last variable in title case as part of print statement
print("Hello, " + full_name.title() + "!")
# step 23 program
# assign string variables
first_name = "katherine"
last_name = "walden"

# use concatenation to create new variable
full_name = first_name + " " + last name

# use concatenation to create new variable
sentence="Hello, " + full_name.title() + "!"

# output last variable
print(sentence)

Combining Variable Types

  1. Python works with integers (whole numbers) and floats (any number with a decimal point). Python uses the basic mathematic symbols to perform functions: + (add), - (subtract), * (multiply), / (divide).

  2. Try this program:

# arithmetic operator examples
print(2+3)
print(2-3)
print(2*3)
print(2/3)
Q4: Why does print(2//3) return 0? How would you modify your code to return the decimal number? Why?
  1. Hint: Try print(2.0//3.0) using the floating point integers (numbers with decimal points).

  2. Let’s write a new program with an integer variable and a string variable. Feel free to modify course number and department if taking this as something other than CSE 10101.

# assign string variable
course_name="Elements of Computing I"

# assign integer variable
course_number = 10101

# concatenation in print statement
print("Welcome to " + course_name.title() + " CSE:" + course_number)
  1. When you run the program, you will receive an error.

  1. The type error is telling us that we cannot use these two different variable types in the same function.

  2. When we want numbers to be read as characters rather than numeric digits, we have to use the string method str() to convert the integer into a string of characters.

# concatenation in print statement, using str function to convert course number
print("Welcome to " + course_name.title() + " CSE:" + str(course_number))
Q5: Explain concatenation in your own words. Why must we convert numbers to strings in the program above? Refer to the examples in step 27 and 30.
# step 27 example
# assign string variable
course_name="Elements of Computing I"

# assign integer variable
course_number = 10101

# concatenation in print statement
print("Welcome to " + course_name.title() + " CSE:" + course_number)
# step 30 example
# concatenation in print statement, using str function to convert course number
print("Welcome to " + course_name.title() + " CSE:" + str(course_number))
Q6: Write a program that converts integer, float, or boolean values to a string, using the str function.

String Length and Access

  1. We can get the length or size of a string by using the len function.
# show length/number of characters in first_name variable
len(first_name)
  1. We can also extract (or isolate) individual characters within a string. To do so, we need a way to specify which character we mean.

  2. This is done by giving each position in the string an index number or index operator, which is determined by simply counting off (starting at 0) from left to right.

  3. We then use the index number as a subscript into the string.

# access first character in string
first_name[0]

# access last character in string
first_name[-1]
  1. In Python there is no notion of a character type as there is in languages such as Java or C. So when we check the type for a character in a string, we get back another string.
# show data type for last character in string
type(first_name[0])
  1. Another example: let's say we have a variable color that includes the string "turquoise".

  2. Then...

  • color[0] holds the letter t
  • color[1] holds the letter u
  • color[2] holds the letter r
  • etc
Q7: Write a program that prompts the user to enter a 6-letter word, and then prints the first, third, and fifth letters of that word.
  1. A sample output for your program might look like this:
Please enter a 6-letter word: joyful
The first, third, and fifth letters are: j y u
  1. NOTE: Strings in Python are immutable, which means that you cannot change the elements of a string once it is set.

  2. The following program will result in a TypeError.

# program that attempts to modify character in a string
first_name[0] = 'k'
  1. So what do you do when you want to update a string? You simply construct a new one!
# reassign first_name variable with modified first character
first_name = 'k' + first_name[1:]

# show reassigned variable
first_name

Other String Operations

  1. Since a string is a sequence of characters, there are a few other operations that work on strings.

Length

  1. We've already seen the len function in action, but to refresh:
# get length of first_name variable
len(first_name)

Properties

  1. We can check the properties of characters in a string.
  • .isalpha() checks if all string values are letters
  • .isalnum() checks if string includes only letters and numbers
  • .isdigit() checks if all string values are numbers
  • .islower() checks if all string includes any lower-case characters
  • .isspace() checks if the string includes any whitespace characters
  • .istitle() checks if the string includes any title-case characters
  • .isupper() checks if the string includes any upper-case characters
  1. To see these string property methods in action in Python syntax:
# checks if all string values are letters
'abc123'.isalpha()

# checks if string values are letters and numbers
'abc123'.isalnum()

# checks if all string values are numbers
'abc123'.isdigit()

# checks if string includes any lower-case characters
'abc123'.islower()

# checks if string includes any whitespace characters
'abc123'.isspace()

# checks if string includes any title-case characters
'abc123'.istitle()

# checks if string includes any upper-case characters
'abc123'.isupper()
  1. These commands return Boolean True or False values.

Sort

  1. We can sort characters in a string alphabetically.
# sort alphabetically
sorted(first_name)
  1. These commands output the characters in the string in alphabetical order.

Max and Min

  1. We can also get the maximum or minimum value in the string.

  2. For strings that are sequences of characters, the minimum value is the character that appears first in the English-language alphabet, and the maximum is the character that appears last in the English-language alphabet.

# get max string letter
max(first_name)

# get min string letter
min(first_name)

in Operator

  1. We can also use the in operator to check if a character or substring (combination of characters) is present in another string.
# checks is 'a' is in 'abcd' string
'a' in 'abcd'

# checks if 'e' is in 'abcd' string
'e' in 'abcd'

# checks if 'bc' is in 'abcd' string
'bc' in 'abcd'
  1. Each of these in operator examples returns a Boolean value, True or False.

Search

  1. We can also instruct the computer to search for a given character within a string.

  2. There are a few different search methods we can use with strings:

  • .startswith() checks if the string starts with a character or substring
  • .endswith() checks if the string ends with a character or substring
  • .find() locates the index position for a specific character or substring
  • .index() also locates the index position for a specific character or substring
  1. NOTE: The .find() method returns -1 if the character or substring is not found. The .index() method will throw an error if the character or substring is not found.

  2. To see these methods in action using Python syntax:

# checks if string starts with 'the' substring
'the boy who blocked his own shot'.startswith('the')

# checks if string ends with 'shot' substring
the boy who blocked his own shot'.endswith('shot')

# locates index position for 'who' substring
# note .find() outputs the index position for the first character in the substring
'the boy who blocked his own shot'.find('who') 

# checks if 'who' substring is located at index position 10
# note -1 return means the substring was not located at that position
'the boy who blocked his own shot'.find('who', 10)

# locates index position for 'who' substring
'the boy who blocked his own shot'.index('who') 

# checks if 'who' substring is located at index position 10
# unlike .find(), .index() will return a ValueError if the substring is located at that position
'the boy who blocked his own shot'.index('who', 10)
  1. Let's look at another example.

  2. Say we have a variable color holds the string "turquoise".

  3. We can retrieve the index of the letter q (which is 3) as follows:

# assign string variable
color = "turquoise"

# get index number of q character
index_number = color.index("q")

# show index number as part of print statement
print ("The index number for the letter q within the word " + color + " is " + index_number)
Q8: Modify the program to have it search for other characters in the string. Does it always return the index number you expect? What index is returned if you ask for the index of the letter u (i.e., what happens when the desired character appears more than once in the string)?
```Python # program you're modifying for Q8 # assign string variable color = "turquoise"

get index number of q character

index_number = color.index("q")

show index number as part of print statement

print ("The index number for the letter q within the word " + color + " is " + index_number)


# Lists

<table>
 <tr><td>
<img src="https://elearn.southampton.ac.uk/wp-content/blogs.dir/sites/64/2021/04/PanPan.png" alt="Panopto logo" width="50"/></td>
  <td><a href="https://notredame.hosted.panopto.com/Panopto/Pages/Viewer.aspx?id=9e9fb874-99d5-4d5b-923b-ad82016231cb">Lists</a></td>
  </tr>
  </table>

60. Python allows us to store information in a few different ways. 

61. In this lab, we're focusing on lists, which are an ordered collection of items.

62. The individual values in a list are called elements or items. 

63. Lists have a type and are also considered values themselves.

## Lists With Numbers

```Python
# create a list containing 4 numbers
[0, 1, 2, 3]

# assign that list to a variable
numbers = [0, 1, 2, 3]

# check types of numbers variable
type(numbers)
  1. Although this is rare, list elements do not need to be the same type.
[0, 1.0, 'a']

List Length and Access

  1. We can use the len function to get the length of a list.
# show length of numbers list
len(numbers)
  1. We can also use the index operator and index position to access and manipulate elements in a list.
# access first item in a list
numbers[0]

# access last item in a list
numbers[-1]
# modify first item in a list
numbers[0] = 'zero'
numbers
  1. A few other notes on index operators:

  2. Indeces can be any integer expression.

  3. A few examples:

# `numbers[0+1]` is the same as `numbers[1]`
numbers[0+1]
numbers[1]

# index position stored as a variable
index = 1
numbers[index]
numbers[1]

# index position as a multiplication product
numbers[index * 2]
numbers[2]
  1. An invalid index will yield an IndexError.
# example of invalid index
numbers[1000]
  1. And as covered with strings, a negative index will start at the end of the list and count right to left.
# access last item in list
numbers[-1]

# access next to last item in list
numbers[-2]

Modifying Lists

  1. While strings are immutable, items in a list can be modified.

  2. An example we've seen before that modifies a single list item.

# modify first item in a list
numbers[0] = 'zero'

# show updated list
numbers

Growing Lists

  1. We can also grow an existing list using the .append() or .extend() methods.
# add integer 4 to end of numbers list
numbers.append(4)

# show updated list
numbers

# add [5,6,7] to end of numbers list
numbers.extend(range(5, 8))

# show updated list
numbers
  1. To unpack what happened in that last bit of code- the range() function returns a sequence of numbers.

  2. The default range() function starts at 0, but in this example we start at 5. The default range() function moves by increments of 1 and stops before a specified number. In our example, range() stops before 8.

A Quick Detour Into range()

  1. The core syntax for range: range(start, stop, step)

  2. You may have expected to see the numbers one to ten printed. This is yet another example of the quirks of working with programming languages.

  3. Python starts with the first number and quits when it reaches the last number of your range. Because it stops at 10, it doesn’t include the 10.

  4. We can actually create lists using range(). In this example we'll wrap the list() function around the range() function to create a list of numbers.

# create list of numbers
numbers = list(range(1,10))

# show list of numbers
print(numbers)
Q9: How would you modify this code to output the full range 1-10?
# program you're modifying for Q9
# create list of numbers
numbers = list(range(1,10))

# show list of numbers
print(numbers)
  1. What if we just wanted the odd numbers in this range?

  2. We could add an additional value to the range function to tell the computer to count by two.

  3. A example that changes the step interval.

# create list of numbers with specific start/stop/step interval values
numbers = list(range(1,11,2))

# show list
print(numbers)
Q10: How would you rewrite the code to include only the even numbers from 1 to 10?
# program you're modifying for Q10
# create list of numbers with specific start/stop/step interval values
numbers = list(range(1,11,2))

# show list
print(numbers)

Deleting Items from Lists

  1. We can delete items from a list using the pop() method or the del statement.
# remove an item at index 0 and return just that item
numbers.pop(0)

# remove an item at index 0
del numbers[0]

Empty Lists

  1. A list with no items is called an empty list.

  2. We can also use the list() argument to create an empty list.

  3. Examples in Python syntax:

# create empty list
[]

# create empty list using list()
list()

Nesting and Sublists

  1. Lists can also contain other lists- this is referred to as nested lists or sub-lists.
# create list with two sub-lists
points = [[0, 1], [2, 3]]

# show list
points

# access first item on list, which is a sublist
points[0]

# access first item WITHIN second item on list; 
# core syntax: list_name[list_item_number][sublist_item_number]
points[1][0]

Other List Operations

Lists and the in Operator

  1. Like with strings, we can use the in operator to test if a list contains a specific value.
# checks if 0 is i numbers
0 in numbers

# checks if 5 is in numbers
5 in numbers
  1. Both of these commands return Boolean True or False statements.

List Concatenation

  1. We can concatenate (or join) two lists using the + operator.
# sample concatenation syntax
[0, 1, 2,] + [3, 4, 5]

Copying

  1. We can copy a list using the * (multiplication) operator.
# sample copy syntax
[0, 1, 2] * 3

Sorting

  1. As with strings, we can sort the items in our list.

  2. We have two options when sorting items in a list.

  3. Sorting a list in-place changes the underlying order of items in the list.

  4. Generating a sorted version of a list does not change the underlying order of items in the list.

  5. Let's look at a few examples using Python syntax.

# create numbers list
numbers = [2, 4, 1, 3]

# sort list in place to update list order
numbers.sort()

# show updated list
numbers
# generate sorted version of list; DOES NOT change underlying order
sorted(numbers)

# will return original list order
numbers

# assign results of sorted() to new variable
sorted_numbers = sorted(numbers)

# show new variable with sorted list
sorted_numbers
Reverse
  1. We can reverse a list using the .reverse() method of the reversed() function.

  2. As with .sort() and sorted(), we have the option to reverse in-place or generate a reversed version of the original list.

  3. To demonstrate using Python syntax:

# create list using range()
numbers = range(0, 7)

# reverse list in-place
numbers.reverse()

# show reversed list
numbers

Utility Functions

  1. A few other functions that come in handy when working with lists that contain numbers.
  • sum() calculates the sum of items in a list
  • max() identifies the highest value in a list
  • min() identifies the lowest value in a list
  • random.choice() selects a list item at random
  • random.shuffle() shuffles items in a list in-place
  • random.sample() samples a select number of items from a list
  1. Examples for each in Python syntax:
# compute the sum of a list
sum([0, 1, 2, 3])

# assign list to variable 
list = ([0, 1, 2, 3])

# compute sum of list using variable name
sum(list)
# find max value of list
max([0, 1, 2, 3])

# find max value of list using variable name
max(list)
# find min value of list
min([0, 1, 2, 3])

# find min value using list variable
min(list)

To use any of the random functions, we would first need to import the random module.

# import random module
import random

# select element at random
random.choice(list)
# shuffle a list in-place
random.shuffle(list)

# show updated/shuffled list
print(list)
# sample 2 elements from a list
# core syntax: random.sample(list_name, number_of_elements)
random.sample(list, 2)

Looking Ahead

  1. In the next lab, we'll talk all about conditional statements.

  2. But for now, let's take a step back and think about how Python interacts with or treats the items in our list.

  3. For example, when we're using the in operator, how does Python test for membership (i.e. see if the value we're looking for is located in the list)?

  4. Python accomplishes this via iteration, which involves iterating over each item in the list.

  5. So Python starts at the first item in the list (index position 0), and goes through each item on the list (left to right) until it reaches the end of the list.

  6. Again, we will have a whole lab on conditional statements, but a few quick examples for now just to illustrate the concept of iteration.

  7. We can use a for loop to iterate over the items in a list.

# sample for loop that iterates over items in list
for number in numbers:
 print(number)
  1. We can iterate over just the indeces in the list.
# sample for loop that iterates over index values for items in list
for i in range(len(numbers)):
 print(number[i])
  1. We can retrieve the item and the index position using the enumerate() function.
# sample for loop that gets list value and index using enumerate
for i, number in enumerate(numbers):
 print(i, number)
  1. Again, more to come on conditional statements and loops.

Lab Notebook Questions on Lists with Numbers

Q11: Create the list numbers with the following values: [[0, 1], [2, 3], [4, 5]].

  • What is the second element?
  • How would you change 4 to 'four'?
  • How would you change 1 to 'one'?
  • How would you print out each sub-list (one sub-list per line)?
  • How would you print out each number (one number per line)?

Q12: Create your own list of numbers. Include your list code as part of this question answer. What is the length of your list? What is the number position for each of the items in your list? How would you return the value of the first item? How would you return the value of the last item?

Q13: Using the same list from the previous question, write a program that includes the following steps or components:

  • Adds a new item to your list
  • Deletes an item from your list
  • Sorts your list in-place
  • Generates a sorted version of your list
  • Reverses your list in-place
  • Determines the min and max values for your list
  • Selects a list element at random
  • Shuffles your list

Lists With Strings

  1. Now let's put lists and strings together.

  2. In the previous section of the lab, we focused on lists consisting of numbers.

  3. Lists can also contain characters, or in this case, strings.

  4. Write a list of a few of your favorite things.

# sample list of strings
cookies = ['chocolate chip', 'snickerdoodle', 'peanut butter', 'sugar']
  1. We can print this list with a print function print(cookies), but Python returns a representation of the list, just as we entered it. ['chocolate chip', 'snickerdoodle', 'peanut butter', 'sugar']

  2. This isn’t particularly useful by itself; however, we can use the position of each item (the index) to perform different functions.

  3. Add a print() function calling a specific item on your list.

# output first item in the list in title case
print(cookies[0].title())
  1. This command returns the first item on my list. This is the item in the 0 position on my list.
Chocolate Chip
  1. Items in a list are indexed with a number, beginning with 0 NOT 1.

  2. A print function that outputs the last item on my list of four items would look like this.

# output fourth item in list in title case
print(cookies[3].title())
  1. We can also work backwards (left-to-right) on our list using negative numbers. For example, to call the last item on the list we could also use the index position -1.
# output last item in list in title case using negative index
print(cookies[-1].title())
  1. To return the second to last item, we could use -2. For the third to last -3, etc.

  2. We can concatenate our list items in strings.

# print statement that includes concatenation
print("My favorite cookie to bake is " + cookies[1].title() + ".")
  1. Which outputs My favorite cookie to bake is snickerdoodle.

  2. We can also change the items in a list.

  3. Maybe I have a friend who is allergic to peanut butter. I can change the peanut butter entry.

# change third item in list
cookies[2] = 'oatmeal'

# show updated list
print(cookies)
  1. The print() function outputs the modified list. ['chocolate chip', 'snickerdoodle', 'oatmeal', 'sugar']

  2. We can also add data to our list using the append function.

# recreate original list
cookies = ['chocolate chip', 'snickerdoodle', 'peanut butter', 'sugar']

# append value to end of list
cookies.append('oatmeal')

# show updated list
print(cookies)
  1. The print() function now returns a list of five items [chocolate chip, snickerdoodle, peanut butter, sugar, oatmeal]

  2. We can also use append() to create new lists.

# create empty list
my_pets = []

# append values to list
my_pets.append('Christy Mathewson')
my_pets.append('Smoky Jo Wood')
my_pets.append('Sandy Koufax')

# show updated list
print(my_pets)
  1. In this block of code, we started with an empty list []. Then the next two lines with append() add new items to the list.

  2. With append(), items are added to the end of the list.

  3. The insert() function allows us to add items to any position in the list.

# create list of fruits
fruit = ['apple', 'pear', 'banana']

# insert new value at specific location
fruit.insert(1, 'orange')

# show updated list
print(fruit)
  1. This block of code adds orange to the second position on the list (index position 1).

  2. The output is ['apple', 'orange', 'kiwi', 'banana']

  3. Conversely, the del statement allows you to delete items from your list using the index number.

  4. The following code will remove orange from the list.

# recreate original list
fruit = ['apple', 'orange', 'pear', 'banana']

# remove second value
del fruit[1]

# show updated list
print(fruit)
  1. We can also delete items by value (instead of position) using remove().
# recreate original list
fruit = ['apple', 'orange', 'pear', 'banana']

# remove specific string
fruit.remove('orange')

# show updated list
print(fruit)
remove only removes the first instance of the value in the list. So, if in the previous example orange appeared on the list a second time, only the first instance would be removed. To remove all instances, you would need to perform a loop (we’ll talk about loops later in the semester).

List Functions and String Elements

  1. Many of the list functions covered in the section of the lab focused on lists with numbers can also work on lists that contain strings.

Len

  1. To find the length of your list, use the len() function.
# recreate original list
fruit = ['apple', 'orange', 'pear', 'banana']

# get length of list and assign to variable
length = len(fruit)

# output length
print(length)
# alternative syntax
len(fruit)

Sort

  1. To alphabetize your list, use the sort() method.
# sort list
fruit.sort()

# show sorted list
print(fruit)

Reverse

  1. To print in reverse order, use reverse().
# reverse sort list
fruit.reverse()

# show sorted list
print(fruit)

Lab Notebook Questions on Lists With Strings

  1. To recap: Lists are an ordered collection of items. Lists can be numbers or strings. They are declared with a variable name, but the information is contained within [ ] and the individual items are separated by a comma.

Q14: Create your own list of strings. Include your list code as part of this question answer. What is the length of your list? What is the number position for each of the items in your list? How would you return the value of the first item? How would you return the value of the last item?

Q15: Using the same list from the previous question, write a program that includes the following steps or components:

  • Adds a new item to your list
  • Deletes an item from your list
  • Sorts your list in-place
  • Generates a sorted version of your list
  • Reverses your list in-place
  • Determines the min and max values for your list
  • Selects a list element at random
  • Shuffles your list

Additional Lab Notebook Questions

Q16: What is the difference between a list and a string? What are some methods you can perform on a list that you can't do with a string (and vice versa)?

Q17: Include a link to your Replit workspace for this lab.

How to submit this lab (and show your work)

Moving forward, we'll submit lab notebooks as .py files.

One option is to have a .py file that you use to run code and test programs while working through the lab. When ready to submit the lab notebook, you add comments and remove extraneous materials.

Another option is to have an "official" .py file that you are using as a lab notebook (separate from your working/testing file). Use comments in Python to note when you are starting a new question (as well as answering a question).

  • Example: Lab5_Notebook_Walden.py

What gets submitted as the lab notebook is the Lab5_Notebook_Walden.py file.

  • When in doubt, use comments
  • Be sure you are using comments to note what question you're responding to

Lab Notebook Questions

Lab notebook template:

Q1: In your own words, explain the difference between print(hello) and print(“hello”).

Q2: Describe the syntax of the following three print() statements in your own words. What is this code doing? Define the function and method for each example.

# Q2 examples
name = "katherine walden"
print(name.title())
print(name.upper())
print(name.lower())

Q3: Explain how each of these programs (steps 20-23) work in your own words.

# step 20 program
# assign string variables
first_name = "katherine"
last_name = "walden"

# use concatenation to create new variable
full_name = first_name + " " + last name

# output last variable
print(full_name)
# step 21 program
# assign string variables
first_name = "katherine"
last_name = "walden"

# use concatenation to create new variable
full_name = first_name + " " + last name

# output last variable in title case as part of print statement
print("Hello, " + full_name.title() + "!")
# step 23 program
# assign string variables
first_name = "katherine"
last_name = "walden"

# use concatenation to create new variable
full_name = first_name + " " + last name

# use concatenation to create new variable
sentence="Hello, " + full_name.title() + "!"

# output last variable
print(sentence)

Q4: Why does print(2//3) return 0? How would you modify your code to return the decimal number? Why?

Q5: Explain concatenation in your own words. Why must we convert numbers to strings in the program above? Refer to the examples in step 27 and 30.

# step 27 example
# assign string variable
course_name="Elements of Computing I"

# assign integer variable
course_number = 10101

# concatenation in print statement
print("Welcome to " + course_name.title() + " CSE:" + course_number)
# step 30 example
# concatenation in print statement, using str function to convert course number
print("Welcome to " + course_name.title() + " CSE:" + str(course_number))

Q6: Write a program that converts integer, float, or boolean values to a string, using the str() function.

Q7: Write a program that prompts the user to enter a 6-letter word, and then prints the first, third, and fifth letters of that word.

Q8: Modify the program to have it search for other characters in the string. Does it always return the index number you expect? What index is returned if you ask for the index of the letter u (i.e., what happens when the desired character appears more than once in the string)?

# program you're modifying for Q8
# assign string variable
color = "turquoise"

# get index number of q character
index_number = color.index("q")

# show index number as part of print statement
print ("The index number for the letter q within the word " + color + " is " + index_number)

Q9: How would you modify this code to output the full range 1-10?

# program you're modifying for Q9
# create list of numbers
numbers = list(range(1,10))

# show list of numbers
print(numbers)

Q10: How would you rewrite the code to include only the even numbers from 1 to 10?

# program you're modifying for Q10
# create list of numbers with specific start/stop/step interval values
numbers = list(range(1,11,2))

# show list
print(numbers)

Q11: Create the list numbers with the following values: [[0, 1], [2, 3], [4, 5]]

  1. What is the second element?
  2. How would you change 4 to 'four'?
  3. How would you change 1 to 'one'?
  4. How would you print out each sub-list (one sub-list per line)?
  5. How would you print out each number (one number per line)?

Q12: Create your own list of numbers. Include your list code as part of this question answer. What is the length of your list? What is the number position for each of the items in your list? How would you return the value of the first item? How would you return the value of the last item?

Q13: Using the same list from the previous question, write a program that includes the following steps or components:

  • Adds a new item to your list
  • Deletes an item from your list
  • Sorts your list in-place
  • Generates a sorted version of your list
  • Reverses your list in-place
  • Determiens the min and max values for your list
  • Selects a list element at random
  • Shuffles your list

Q14: Create your own list of strings. Include your list code as part of this question answer. What is the length of your list? What is the number position for each of the items in your list? How would you return the value of the first item? How would you return the value of the last item?

Q15: Using the same list from the previous question, write a program that includes the following steps or components:

  • Adds a new item to your list
  • Deletes an item from your list
  • Sorts your list in-place
  • Generates a sorted version of your list
  • Reverses your list in-place
  • Determines the min and max values for your list
  • Selects a list element at random
  • Shuffles your list

Q16: What is the difference between a list and a string? What are some methods you can perform on a list that you can't do with a string (and vice versa)?

Q17: Include a link to your Replit workspace for this lab.

About

Lists and Strings in Python (Elements of Computing I, University of Notre Dame)

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published