Computation for Linguists

Beginning Python: More Tricks with Lists, While Loops

Dr. Andrew M. Byrd

2025-10-10

Review

  • What did you learn last time?

Recap from Last Time

  • Conditionals: if = 1 x
  • Loops: for = multiple times
  • Cleaning text with .strip(), .lower()

Review Activity

  • Copy this list of messy words into your code, creating a list called words:
words = [" Cat\n", "dog", " BIRD ", "fish\n", "LION", "tiger ", "bear", "OWL\n"]
  • Write a for loop that goes through each word. Inside the loop:
    • Use .strip() and .lower() to clean the word
    • Save each result in a variable called cleaned
    • Print each instance of cleaned in the loop.

More Tricks with Lists

.append()

  • In the previous activity, we were able to print up each cleaned word
  • But what if we want the words to remain in a list?
  • For this, we’ll use the method .append()
test_list = ["a", "b", "c"]
test_list.append("d")

Review Activity - Revisited

  • Here is one way that we could have done the review activity:
words = [" Cat\n", "dog", " BIRD ", "fish\n", "LION", "tiger ", "bear", "OWL\n"]

for word in words:
    cleaned = word.strip().lower()
    print(cleaned)

Review Activity - Revisited

  • But how to maintain these words in a list?

  • First, more straightforward (but less efficient) way:

words = [" Cat\n", "dog", " BIRD ", "fish\n", "LION", "tiger ", "bear", "OWL\n"]
cleaned_words = []

for word in words:
    cleaned = word.strip().lower()
    cleaned_words.append(cleaned)

print(cleaned_words)
  • Here we used the .append() method

Review Activity - Revisited

  • Second, more efficient but trickier way is to use a list comprehension, through which we don’t even have to use .append():
words = [" Cat\n", "dog", " BIRD ", "fish\n", "LION", "tiger ", "bear", "OWL\n"]

cleaned_words = [word.strip().lower() for word in words]

print(cleaned_words)

Counters

  • In Linguistics, we often want to know how many words are in a text or how many sounds are in a word.
  • We could use the len() command:
items = ["color", "flavour", "theater", "center", "analyze", "organize", "favorite", "neighbor", "honor", "catalog", "honour", "flavor", "analyse", "flavor", "traveler"]
print(len(items))

Counters

  • Or we could create a counter, to count how many items there are:
items = ["color", "flavour", "theater", "center", "analyze", "organize", "favorite", "neighbor", "honor", "catalog", "honour", "flavor", "analyse", "flavor", "traveler"]

item_count = 0
for item in items:
    item_count += 1
    print(item, item_count)

Counters

  • We can do much more interesting things with counters, such as:
items = ["color", "flavour", "theater", "center", "analyze", "organize", "favorite", "neighbor", "honor", "catalog", "honour", "flavor", "analyse", "flavor", "traveler"]

c_item_count = 0
for item in items:
    if item[0] == "c":
        c_item_count += 1
        print(item, c_item_count)

Counter Activity

  • Identify how many words end in “r” in the following list:
items = ["color", "flavour", "theater", "center", "analyze", "organize", "favorite", "neighbor", "honor", "catalog", "honour", "flavor", "analyse", "flavor", "traveler"]

If you’re like me, you might be confused by:

  • Index vs. Integer
word = "word"
word[0]
numb = 0

.replace()

  • Let’s return to our items list
  • Notice some inconsistencies in spellings?
items = ["color", "flavour", "theater", "center", "analyze", "organize", "favorite", "neighbor", "honor", "catalog", "honour", "flavor", "analyse", "flavor", "traveler"]

.replace()

  • A method to replace one string with another.
word = "four"
new_word  = word.replace("our", "or")
print(new_word)

.replace()

  • Let’s broaden the scope so that it applies to all words ending in “-our”
items = ["color", "flavour", "theater", "center", "analyze", "organize", "favorite", "neighbor", "honor", "catalog", "honour", "flavor", "analyse", "flavor", "traveler"]

down_with_brits = []
for word in items:
    if word.endswith("our"):
        word = word.replace("our", "or")
    down_with_brits.append(word)

print(down_with_brits)
  • Note the .endswith() method - there’s also .startswith()

.replace() Activity

  • Broaden your if block to have words ending in “-yse” respelled as “-yze”

.split()

  • We can also take a line of text and split it up into a list.
getty = "Four score and seven years ago our fathers brought forth on this continent, a new nation, conceived in Liberty, and dedicated to the proposition that all men are created equal."

getty.split()
  • By default, split() separates according to whitespace.

.split()

  • But what happens if you do the following?
getty = "Four score and seven years ago our fathers brought forth on this continent, a new nation, conceived in Liberty, and dedicated to the proposition that all men are created equal."

getty_1 = getty.split(",")
getty_2 = getty.split(".")
getty_3 = getty.split("e")
print(getty_1, "\n", getty_2, "\n", getty_3)

re.split()

  • How would you split according to whitespace and punctuation?
  • Our old friend regex
  • Create a new codeblock and paste this code (you may have to create a separate .py file):
import re

text = "Hello, world!   This... is a test."
words = re.split(r"[\s\W]+", text)
words = [w for w in words if w]
print(words)

re.split()

import re

text = "Hello, world!   This... is a test."
words = re.split(r"[\s\W]+", text)
words = [w for w in words if w]
print(words)
  • \s = whitespace
  • \W = non-word characters (punctuation, symbols, etc.)
  • + = one or more preceding

re.split()

  • Revisit your file alice.txt (found at https://www.gutenberg.org/cache/epub/11/pg11.txt)
  • Load up alice.txt in Python using the following code:
with open("alice.txt", "r", encoding="utf-8") as f:
    alice_text = f.read()
  • Using re.split() create a new list called alice_list, containing all words, minus whitespace and non-word characters
  • Confirm it worked by using print(alice_text[0:100])

while Loops

while Loops

  • They’re a lot like if statements, where something happens if a condition is met:
x = 0
if x < 10:
    print(x, "is less than 10.")

while Loops

  • In while loops, there’s also a logical condition
  • But instead of running the code once, python will loop back and recheck the conditional
  • It will do this forever until the conditional returns False
x = 10
while x < 10:
    print(x, "is less than 10.")
    x = x + 1

while Loops

  • Be careful with while loops! Code (like below) will run ad infinitum and could crash your computer:
x = 0
while x < 10:
    print(x, "is less than 10.")
    x = x - 1

while Loops

  • In this class, we will mostly use for loops
  • But you can do some interesting things with while loops, like:
name = "The University of Kentucky"
while name: 
      print("|" + name + "|") 
      name = name[0:-1]

Activity Answers

Review Activity


words = [" Cat\n", "dog", " BIRD ", "fish\n", "LION", "tiger ", "bear", "OWL\n"]

for word in words:
    cleaned = word.strip().lower()
    print(cleaned)

Counter Activity

items = ["color", "flavour", "theater", "center", "analyze", "organize", "favorite", "neighbor", "honor", "catalog", "honour", "flavor", "analyse", "flavor", "traveler"]

r_item_count = 0
for item in items:
    if item[-1] == "r":
        r_item_count += 1
        print(item, r_item_count)

.replace() Activity

items = ["color", "flavour", "theater", "center", "analyze", "organize", "favorite", "neighbor", "honor", "catalog", "honour", "flavor", "analyse", "flavor", "traveler"]

down_with_brits = []
for word in items: 
    if word.endswith("our"): 
        word = word.replace("our", "or") 
    elif word.endswith("yse"): 
        word = word.replace("yse", "yze") 
    down_with_brits.append(word)
print(down_with_brits)

.re.split() Activity


import re
with open("alice.txt", "r", encoding="utf-8") as f:
    alice_text = f.read()
alice_list = re.split(r"[\s\W]+", alice_text)
alice_list = [w for w in alice_list if w]
print(alice_list[0:100])