Data Types

Lab 02 Solutions

Author

Romi Hill

Published

September 24, 2026

1 Types

  1. Before you run the code in Python, think about what the expected output of these commands is. Once you’ve thought about it, run the code.
type(10.5)
float
type(10)
int
type("7.3")
str
type(8 + 38.1)
float
type([10, 5])
list
type("hello")
str
type(print("hello"))
hello
NoneType
  1. What happens when you try to apply arithmetic operator to different data types? You can use your previously defined variables to answer this question!
my_lst = [1, 2, 3]
my_int = 5
my_str = "hello"

1. What happens when you multiply a `list` with an `int`?

my_lst * my_int
[1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3]

2. What happens when you add a `list` with an `int`?

my_lst + my_int 
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
Cell In[10], line 1
----> 1 my_lst + my_int

TypeError: can only concatenate list (not "int") to list

3. What happens when you multiply a `str` with an `int`?

my_str * my_int
'hellohellohellohellohello'

4. What happens when you add a str with an int?

my_str + my_int
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
Cell In[12], line 1
----> 1 my_str + my_int

TypeError: can only concatenate str (not "int") to str

5. What happens when you add a str with an list?

my_str + my_lst
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
Cell In[13], line 1
----> 1 my_str + my_lst

TypeError: can only concatenate str (not "list") to str

For example, what happens when you run the following code?

my_lst * my_int

The take away message here: When you apply an operator to two different data types, the output might not be obvious! Some operations will work (though it’s not always clear what the final data type will be), while others will raise an error. If it is successful, then the one of the types will be converted to the other. This is called implicit type casting. You can read more about this here.

But if you cannot be bothered/not interested, you should still always check what happens when you combine two data types. Or better yet, you can type cast to make explicit what you’re trying to do!

2 Type Casting

You can also explicitly convert data types.

What do the following operations do?

int(-7.3)
-7
list('hello')
['h', 'e', 'l', 'l', 'o']
set([1, 2, 2, 4, 5])
{1, 2, 4, 5}
set(str(7.375) + str(45))
{'.', '3', '4', '5', '7'}

3 Operations on Lists

We can index lists.

my_lst = [17, 22, 'a', 'r', True]
my_lst[2]
'a'
my_lst[0]
17
my_lst[-1]
True

We can slice lists.

my_lst[:2]
[17, 22]
my_lst[1:3]
[22, 'a']

We can specify the steps

my_lst[::2]
[17, 'a', True]

We can reverse lists

my_lst[::-1]
[True, 'r', 'a', 22, 17]

We can reverse and specify the number of steps

my_lst[::-2]
[True, 'a', 17]

4 Functions

Recall functions:

def frequency(corpus, word):
    """
    Calculates the relative frequency of a word within a corpus. 

    :param corpus: An NLTK Text containing a corpus
    :param word: A word to search for in the corpus

    :return: The proportion of words in corpus that match word
    """
    return corpus.count(word) / len(corpus)
  1. What is a function? What are some of the components of a function?

  2. Write a function that outputs the following

print_hello('Romi')
'Hello Romi!'

I’ll give you the start. Hint: you need to use an operator.

Solution:

def print_hello(name):
    print('Hello ' + name + '!')

Additional Exercise:

Modify the code so that the default value is “Sophie”. That is, your function should have the following output given these inputs. This should only take 9 characters to type!

Solution:

def print_hello(name = "Sophie"):
    return 'Hello ' + name + '!'
print_hello()
'Hello Sophie!'
print_hello("class of LX394")
'Hello class of LX394!'

5 Putting it together: Functions, Palindrones, and Anagrams

  1. Based on the code provided below, write a function that returns True when x and y are anagrams of each other, and false otherwise. Example input and expected output is provided below.

Note: You may have noticed : str and -> bool in this sample code. It’s good style to yourself/anyone else using the code that the input parameters should be a str, and the output should be a bool. However, this is not necessary. In fact, Python will still run if the output is not a bool, for example.

def is_anagram(first_word: str, second_word: str) -> bool:
    """
    Check whether two strings are anagrams of each other. 
    An anagram is formed by rearranging the letters of one word to produce another.
    """
    pass

Possible Solutions:

If there are no duplicates, we can use set() to check if the two words are anagrams of each other.

def is_anagram(first_word: str, second_word: str) -> bool:
    """
    Check whether two strings are anagrams of each other. 
    An anagram is formed by rearranging the letters of one word to produce another.
    """
    return set(first_word) == set(second_word)

If there are duplicates, we can use sorted() to check if the two words are anagrams of each other.

def is_anagram(first_word: str, second_word: str) -> bool:
    """
    Check whether two strings are anagrams of each other. 
    An anagram is formed by rearranging the letters of one word to produce another.
    """
    first_word = list(first_word)
    second_word = list(second_word)
    if sorted(first_word) == sorted(second_word):
        return True
    else:
        return False

If you want to be concise, you can also write the above code as:

def is_anagram(first_word: str, second_word: str) -> bool:
    """
    Check whether two strings are anagrams of each other. 
    An anagram is formed by rearranging the letters of one word to produce another.
    """
    return sorted(list(first_word)) == sorted(list(second_word))
is_anagram('listen', 'silent')
True
is_anagram('listen', 'listened')
False

Challenge question:

Modify your code so that it also ignores spaces and capitalization.

Solution:

is_anagram('Listen', 'siLeNt')
True
is_anagram('Tom Marvolo Riddle', 'I am Lord Voldemort')
True
  1. Based on the code provided below, write a function that returns True when x is a palindrome. Example input and expected output is provided below.

Solution:

def is_palindrone(word: str) -> bool:
    """
    Check whether a word is a palindrone
    A palindrome is a word that is spelt the same backwards and forward 
    """
    return word == word[::-1]
is_palindrone('racecar')
True
is_palindrone('hello')
False