02 More Basic Types
02 More Basic Types
September 2, 2023
# In this unit we will focus on additional, slightly more complex data types
# We will learn about the following data types: string, list, tuple, set, and␣
↪dict (dictionary)
# Strings are iterable, which means that you can loop over them
# Strings are indexed, which means that you can access individual characters
1
''' print(string_name[a:b] )''' # This will print characters in the string from
# a to b-1
print(f"The first three characters of the string are: {citizens[0:3]}")
number = 42
number_str = str(number) # str() Converts other datatype to string
print(number_str) # Output: "42"
name = "Alia"
age = 25
message = "My name is {} and I am {} years old.".format(name, age)
print(message) # Output: "My name is Alia and I am 25 years old."
2
print(words) # Output: ["Hello", "World!"]
13
42
My name is Alia and I am 25 years old.
hello, world!
HELLO, WORLD!
Some text
['Hello', 'World!']
Hello, World!
Hi, World!
7
[5]: # In addition to the above built-in functions, there are many more functions␣
↪that can be used on strings
# These functions are defined as member functions of the Class 'str' (We will␣
↪learn more about 'class' in a later unit)
# and they can be accessed using a dot operator '.' as shown below
# Visit this link to review these member functions and try them out here ...
HELLO, WORLD!
3
try:
my_string[0] = 'h' # This will raise a TypeError
except TypeError as e:
print(f"Error: {e}")
# Q: If strings are immutable, what will you do if you have to modify a string?
''' use inbuilt string methods like : string.replace( "hello" , "hi" )'''
# Q: Is it possible to convert 123 to its English text 'one hundred and twenty␣
↪three'? And vice-versa?
number = 123
text_representation = num2words(number)
print(text_representation) # Output: 'one hundred and twenty-three'
1 LISTS
[7]: # Lists
# Python lists are mutable, which means that you can change the elements of the␣
↪list after it is created
# Lists are iterable, which means that you can loop over them ... as explained␣
↪later
# Visit the documentation and try the functions by coding examples here ...
4
[9]: # List ... examples
# You can also use negative indexes to access elements from the end of the list.
# For example, fruits[-1] will access the last element in the list.
print("Printing the last element using negative indexing:", fruits[-1])
# You can use the `len()` function to get the length of a list.
print("The length of the list is:", len(fruits))
[10]: # As in the case of strings, a number of list member functions (also known as␣
↪methods) can be used
# This documentation also outlines various uses of the list data type
# You can use the `append()` method to add elements to the end of a list.
fruits.append("orange")
print("The list after appending 'orange':", fruits)
# You can use the `insert()` method to insert elements into a list at a␣
↪specific index.
fruits.insert(1, "grapes")
print("The list after inserting 'grapes' at index 1:", fruits)
# You can use the `remove()` method to remove elements from a list.
fruits.remove("banana")
print("The list after removing 'banana':", fruits)
# You can use the `sort()` method to sort the elements in a list.
fruits.sort()
5
print("The sorted list:", fruits)
# You can use the `reverse()` method to reverse the order of the elements in a␣
↪list.
fruits.reverse()
print("The reversed list:", fruits)
# Initialize a list
list_of_numbers = [1, 2, 3, 4, 5]
# Write the list to a file ... note that the file will store the list as binary␣
↪data
[13]: # A list is useful in many ways, starting with its ability to store multiple␣
↪items in a single variable
# It can be used to initiaize more complex structures like matrices ... we will␣
↪do all this soon ...
6
2 Tuples
[14]: # tuples
a_tuple = ("Anita", 25, 155, "F", "Mumbai") # This is how a tuple is defined
a_new_tuple = tuple(["Anita", 25, 155, "F", "Mumbai"]) # It can also be created␣
↪from a list
# Properties of tuples:
# immutable, which means that they cannot be changed after they are created
# iterable, which means that you can loop over them, operating on each element
# indexed, which means that you can access individual elements using square␣
↪brackets
3 Dictionary
[16]: # dict
7
# print(a_dict[0]) # why does this result in an error?
4 Set
[26]: # set
print(a_set)
print(b_set)
8
# on the collection
'''Initialization'''
my_set = {1, 2, 3} # Using curly braces
my_set = set([1, 2, 3]) # Using the set() constructor
'''Adding Elements'''
my_set.add(4) # Adds a single element
my_set.update([5, 6]) # Adds multiple elements. Note the use of a 'list' to␣
↪add multiple elements
'''Removing Elements'''
my_set.remove(3) # Removes a specific element
my_set.discard(2) # Removes a specific element (no error if not present)
print("Popped element" , my_set.pop()) # Removes and returns an arbitrary␣
↪element
element = 4
print(element in my_set) # Returns True if element is in the set, False␣
↪otherwise
9
Popped element 1
Updated my_set {4, 5, 6}
Union set {3, 4, 5, 6}
{4, 5, 6}
set()
{3}
True
3
set()
# We need to also understand the basic program structure to really get going␣
↪with Python
10