0% found this document useful (0 votes)
15 views

02 More Basic Types

Uploaded by

Divyanshu Suman
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views

02 More Basic Types

Uploaded by

Divyanshu Suman
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 10

02-more-basic-types

September 2, 2023

[1]: # Welcome back!

# 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)

# These data types are known as Sequence Types

[2]: # str ... strings

# This is a data type, and it is used to store text. In Python,


# Strings are enclosed in single or double quotes
# Strings are immutable, which means that they cannot be changed after they␣
↪are created

# Strings are iterable, which means that you can loop over them
# Strings are indexed, which means that you can access individual characters

# They can be manipulated, concatenated, split, compared, etc. using various␣


↪operators and functions

# Python documentation on strings is available at: https://docs.python.org/3/


↪library/stdtypes.html#text-sequence-type-str

[3]: # Examples ...

name_1 = "Nagrik Gaowala"


name_2 = 'Nagrik Shaharwala'

citizens = name_1 + " and " + name_2 # Concatenation


print(f"The following are citizens: {citizens}")

str_len = len(citizens) # Length of the string


print(f"The length of the string is: {str_len}")

# Example of string indexing ... Note: Indexing starts at 0


print(f"The first character of the string is: {citizens[0]}")

# Example of string slicing :

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]}")

# Example of string slicing from the end


print(f"The last three characters of the string are: {citizens[-3:]}")

The following are citizens: Nagrik Gaowala and Nagrik Shaharwala


The length of the string is: 36
The first character of the string is: N
The first three characters of the string are: Nag
The last three characters of the string are: ala

[4]: # The following built-in functions of Python can be used on strings


# len(), str(), format(), strip(), split(), join(), upper(), lower(),␣
↪replace(), find()

# A list of these built-in functions is available at https://docs.python.org/3/


↪library/functions.html

text = "Hello, World!"


length = len(text)
print(length) # Output: 13

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."

text = "Hello, World!"


lowercase_text = text.lower()
print(lowercase_text) # Output: "hello, world!"

text = "Hello, World!"


uppercase_text = text.upper()
print(uppercase_text) # Output: "HELLO, WORLD!"

text = " Some text "


stripped_text = text.strip() # Strips extra spaces at the start and end
print(stripped_text) # Output: "Some text"

text = "Hello, World!"


words = text.split(", ") # split the string into a LIST using the delimiters␣
↪',' and '<space>

2
print(words) # Output: ["Hello", "World!"]

words = ["Hello", "World!"] # ["Hello", "World!"] is a list, more about␣


↪lists soon

text = ", ".join(words)


print(text) # Output: "Hello, World!"

text = "Hello, World!"


new_text = text.replace("Hello", "Hi")
print(new_text) # Output: "Hi, World!"

text = "Hello, World!"


index = text.find("W") # find the index of the first occurrence
print(index) # Output: 7

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

text = "Hello, World!"


print(text.upper()) # Output: "HELLO, WORLD!"

# The member functions are too numerous to be enumerated here!


# They are documented at https://docs.python.org/3/library/stdtypes.
↪html#text-sequence-type-str

# Visit this link to review these member functions and try them out here ...

HELLO, WORLD!

[23]: # Q: What is the meaning of the word 'immutable'? :


''' it means that to change the string we can redefine it
but we cannot change it indexwise'''
# Q: How will you prove that a Python string, once defined, is immutable?
my_string = "Hello"

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?

from num2words import num2words

number = 123
text_representation = num2words(number)
print(text_representation) # Output: 'one hundred and twenty-three'

Error: 'str' object does not support item assignment


one hundred and twenty-three

1 LISTS
[7]: # Lists

# Lists are used to store multiple items in a single variable.


# In Python a list is enclosed within square brackets ... [a,b,c,d]
# A list can be mixed.
# It can contain variables of different data types ... [1, 'hello', True, 3.
↪14, [1,2,3]]

# 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

# Python documentation on lists is available at:


# https://docs.python.org/3/tutorial/introduction.html#lists
# https://docs.python.org/3/tutorial/datastructures.html

[8]: # The following built-in functions of Python can be used on lists


# len(), append(), insert(), remove(), reverse(), sort()
# A list of these built-in functions is available at https://docs.python.org/3/
↪library/functions.html

# Visit the documentation and try the functions by coding examples here ...

4
[9]: # List ... examples

fruits = ["apple", "banana", "mango"]


print("Printing the entire list:",fruits)

# Individual elements in a list can be accessed using square brackets


# Note: The index starts at 0, and goes up to "the length of the list minus 1"
print("Printing only the first element:",fruits[0])
print("Printing only the last element:", fruits[len(fruits)-1])

# 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))

Printing the entire list: ['apple', 'banana', 'mango']


Printing only the first element: apple
Printing only the last element: mango
Printing the last element using negative indexing: mango
The length of the list is: 3

[10]: # As in the case of strings, a number of list member functions (also known as␣
↪methods) can be used

# list methods are documented at : https://docs.python.org/3/tutorial/


↪datastructures.html#more-on-lists

# This documentation also outlines various uses of the list data type

[11]: # Some of the member functions in action ...

# 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)

The list after appending 'orange': ['apple', 'banana', 'mango', 'orange']


The list after inserting 'grapes' at index 1: ['apple', 'grapes', 'banana',
'mango', 'orange']
The list after removing 'banana': ['apple', 'grapes', 'mango', 'orange']
The sorted list: ['apple', 'grapes', 'mango', 'orange']
The reversed list: ['orange', 'mango', 'grapes', 'apple']

[12]: # List I/O

# 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

with open("list_of_numbers.txt", "wb") as file:


file.write(bytes(list_of_numbers))

# Read the list back from the file


with open("list_of_numbers.txt", "rb") as file:
new_list_of_numbers = file.read()
new_list_of_numbers = list(new_list_of_numbers)

# Print the list


print("The list of numbers is:", new_list_of_numbers)

The list of numbers is: [1, 2, 3, 4, 5]

[13]: # A list is useful in many ways, starting with its ability to store multiple␣
↪items in a single variable

# Once a list is created it can be iterated over ... a definite improvement␣


↪over more traditional for loops

# It can be used to initiaize more complex structures like matrices ... we will␣
↪do all this soon ...

6
2 Tuples
[14]: # tuples

# It can also store multiple datatypes

# In programming, a tuple is used to group related data together


# It is a special kind of list, where the collection has a definite meaning
# For example, a row of an Excel spreadsheet is a tuple
# Example: (name,age,height,weight,gender,city) is a tuple, a 'record', a␣
↪special list

# Therefore, once a tuple is defined, it cannot be changed

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

[15]: # The tuple class is documented at https://docs.python.org/3/library/stdtypes.


↪html#tuples

# A number of sequence operators operate on tuples


# They are documented at: https://docs.python.org/3/library/stdtypes.
↪html#common-sequence-operations

# these operators are also applicable to lists

3 Dictionary
[16]: # dict

# A dictionary is a collection of 'key-value' pairs.


# Again, it is a special kind of list, where items are accessible using keys␣
↪instead of an index

# A dictionary is 'mutable', which means that items in it can be changed


# a dictionary is created by collecting together 'key-value' pairs using braces␣
↪: {key1: value1, key2: value2, ...}

# and items are accessed using the key as a reference

a_dict = {"name": "Alia", "age": 25, "city": "Mumbai"}


print(a_dict)
print(a_dict["name"])

7
# print(a_dict[0]) # why does this result in an error?

# Adding a new 'key - value' pair into the dictionary


a_dict["gender"] = "F"
print(a_dict)

# A dictionary is very useful in the following contexts and applications:


# To create a mapping. Eg. Country -> Capital
# To store processed data. Eg. word frequency {"and":250, "the":100, "is":50}
# Configuration settings. Eg. {"host":"localhost", "port":8080}

# All this helps in fast retrieval of data

{'name': 'Alia', 'age': 25, 'city': 'Mumbai'}


Alia
{'name': 'Alia', 'age': 25, 'city': 'Mumbai', 'gender': 'F'}

[17]: # dict class is documented at https://docs.python.org/3/library/stdtypes.


↪html#mapping-types-dict

# It also lists the built-in and member functions of dictionaries

4 Set
[26]: # set

# A set is a collection of unique items


# Again, it is a special kind of dict, with only 'keys'
# In a set, there can be no repetition of items ( doesn't give error ,
# it stores only one instance in case of a repition)

# A set is created using braces ( Curly braces) : {key1, key2, ...}


# and items are accessed using the index as a reference

a_set = {1, "two", 3.14, True}


b_set = {1, 1,"two", 3.14, True} #b_set will have only 1 only one time

print(a_set)
print(b_set)

print(3.14 in a_set) # To check existence of an item in a set


print(3.15 in a_set)

# A set is useful wherever it is clear that a collection of items is a␣


↪mathematical 'set'

# and 'set' operations like union, intersection, difference, membership-checks␣


↪need to be performed

8
# on the collection

{1, 3.14, 'two'}


{1, 3.14, 'two'}
True
False

[37]: # Some quick examples of sets and operations on sets

'''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

'''Operations with 2 sets'''


print("Updated my_set" , my_set)
other_set = {3, 4, 5, 6}
print("Union set" , my_set.union(other_set) ) # Returns a new set with all␣
↪elements from both sets

print(my_set.intersection(other_set)) # Returns a new set with common elements

print(my_set.difference(other_set) ) # Returns a new set with elements in␣


↪my_set but not in other_set

print(my_set.symmetric_difference(other_set)) # Returns a new set with␣


↪elements in either set but not both

element = 4
print(element in my_set) # Returns True if element is in the set, False␣
↪otherwise

length_of_set = len(my_set) # Returns the number of elements in the set


print(length_of_set)
my_set.clear() # Removes all elements from the set
print(my_set)

9
Popped element 1
Updated my_set {4, 5, 6}
Union set {3, 4, 5, 6}
{4, 5, 6}
set()
{3}
True
3
set()

[20]: # That's it, in this module


# While we have covered the basic data like strings, numbers, lists, tuples,␣
↪dicts and sets

# We need to also understand the basic program structure to really get going␣
↪with Python

# That will be the goal of the next unit

10

You might also like