Introduction to Python — Day 2/3

Sudh Bhoi
5 min readMay 24, 2020

--

< Day 1: Python Basics

Structured Types

[~Arrays~] Lists

Here’s where things really start to get a lot better than C. Python arrays (more appropriately known as lists) are not fixed in size; they can grow or shrink as needed, and you can always tack extra elements onto your array and splice things in and out easily.

Declaring a list is pretty straightforward.

nums = []                       # empty list
nums = [1, 2, 3, 4] # explicitly created list
nums = [x for x in range(500)] # list comprehension
nums = list() # empty list using list()

Operations on lists

Tacking on an existing list can be done in few ways.

nums = [1, 2, 3, 4]

nums.append(5)             # append 5
nums.insert(4, 5) # insert 5 at index 4
nums[len(nums):] = [5, 6] # splicing another list [5, 6] onto nums
nums = nums + [5, 6] # concatenation using + operator
nums.extend([5, 6]) # extends nums to [1, 2, 3, 4, 5, 6]

Note that the list are ordered, mutable sequence of data. They usually contain homogeneous elements (i.e. all integers), but can contain mixed types too.

Remove elements of the list.

del(num[index])        # deletes element at specific index
nums.pop() # removes element at end of the list
nums.remove(element) # removes a specific element

Note that if the element occurs multiple times, remove(element) removes first occurrence. But, if element is not in the list it gives an error.

Iterating over lists

Consider the example of computing the sum of elements of a list. A common pattern would be.

total = 0
for i in range(len(nums)):
total += nums[i]
print(total)

Like strings, you can also iterate over list elements directly.

total = 0
for i in nums:
total += I
print(total)

Converting lists to strings and back

You can convert strings to lists with list(str). It returns a string with every character from str an element in list.

Also, str.split() can be used to split a string on a character parameter. If passed without a parameter it splits on spaces.

str = “I <3 CS”        # str is a string
list(str) # returns [‘I’,’ ’,’<’,’3’,’ ’,’C’,’S’]
str.split(‘<’) # returns [‘I’,’3 CS’]

To turn a list of characters into a string, you can use ‘’.join(L), where, character given in quotes is added between every element.

L = [‘a’,’b’,’c’]‘’.join(L)             # returns “abc”
‘_’.join(L) # returns “a_b_c”

Sorting Lists

Calling sort() mutates the list, and returns nothing.
Calling sorted() does not mutate list, therefore you must assign the result to a variable.

L.sort()               # mutates L
AL = sorted(L) # does not mutate L

Tuples

Tuples are ordered, immutable sets of data; they are great for associating collections of data (of different types), but where those values are unlikely to change.

te = ()                # empty tuplet = (2,”one”,3)
t[0] # evaluates to 2
(2,”one”,3) + (5,6) # evaluates to (2,”one”,3,5,6)t[1:2] # slice tuple, evaluates to (”one”,)
t[1:3] # slice tuple, evaluates to (“one”, 3)
t[1] = 4 # error, cannot modify a tuple

Note that the extra comma in (“one”,) represents a tuple with one element.

The following code creates a list of tuples and then iterates over each of them.

pizzas = [
(“cheese”, 150),
(“chicken”, 200),
(“vegetable”, 170)
]
for pizza, cost in pizzas:
print(“Rs. {1} is the cost of {0} pizza”.format(pizza, year))

# Rs. 150 is the cost of cheese pizza
# Rs. 200 is the cost of chicken pizza
# Rs. 170 is the cost of vegetable pizza

Tuples can be conveniently used to swap elements.

(x, y) = (y, x)

Dictionaries

Python also has built in support for dictionaries, allowing you to specify list indices with words or phrases (keys), instead of integers, which you were restricted to in C.

pizzas = {
“cheese”: 150,
“chicken”: 200,
“vegetable”: 170
}

Add/Change Entry

pizza[“cheese”] = 120     # changing “cheese” value to 120
pizza[“bacon”] = 140 # adding “bacon”: 140 to pizzas

Test if key in the dictionary

“cheese” in pizzas        # returns True
“egg” in pizzas # returns False

Delete entry

del(pizzas[“cheese”])

Get an iterable of all keys

pizzas.keys() 
# returns [“cheese”, “chicken”, “vegetable”]

Get an iterable of all values

pizza.values()            # returns [150, 170, 200]

Note that although values can be immutable and mutable type, keys must be unique and of immutable type.

The for loop in Python is extremely flexible!

for pie in pizzas:
print(pie)
# cheese
# chicken
# vegetable
# bacon
for pie, price in pizzas.items():
print(price)
# 170
# 120
# 140
# 200

Objects

Everything in Python is an object and has type.

C structures contain a number of fields, which we might also call properties. But the properties themselves can not ever stand on their own.

C Structure

Objects, meanwhile, have properties but also methods, or functions that are inherent to the object, and mean nothing outside of it. You define the methods inside the object also. Thus, properties and methods don’t ever stand on their own.

You define a type of object using the class keyword in Python. Classes require an initialisation function, also more-generally known as a constructor, which sets the starting values of the properties of the object. In defining each method of an object, self should be its first parameter, which stipulates on what object the method is called.

Syntax:

class ClassName(ParentClass):
<define attributes here>

Example:

class Student():

def __init__(self, name, id):
self.name = name
self.id = id
def changeID(self, id):
self.id = id
def print(self):
print(“{} — {}”.format(self.name, self.id))

jane = Student(“Jane”, 10) # jane is object of class Student
jane.print()
jane.changeID(11)
jane.print()
Jane — 10
Jane — 11

If we try to print the object jane Python calls the __str__ method which by default prints

In [0]: print(Jane)
Out[0]: <__main__.Student object at 0x7fa918510488>

To define your own print method,

class Student():

def __str__(self):
return self.name + “-” + self.id

harry = Student(“Harry”, 21)
print(harry)
# Harry — 21

Special operators

Like print you can also override +, -, ==, <, >, len() and many others.

__add__(self, other)       # self + other
__sub__(self, other) # self — other
__eq__(self, other) # self == other
__lt__(self, other) # self < other
__len__(self) # len(self)

Programming Assignment

Question 0

Write a program to implement fibonacci with a dictionary.

Question 1

  1. Write 2 functions to analyse the lyrics of your favourite song.
  2. Create a frequency dictionary for mapping the str:int.
  3. Find word that occurs the most and how many times.
  • Use a list in case there is more than one word
  • Return a tuple (list, int) for (words_list, highest_freq)

Question 2

Write a recursive program to implement GCD of two given numbers.

Question 3

Write a program to create a new type to represent a collection of integers

  • Initially the set is empty
  • A particular integer appears only once in a set

(Functions/Interface:

  • insert(e) — insert integer e into the set if not there
  • member(e) — return True if e is in set, False else
  • remove(e) — remove integer e from set, error if not present)

Question 4

Write a program that sorts a given list of integers using Bubble Sorting Algorithm.

--

--