Skip to main content

Chapter 3: Functions, Data Structures and Strings

MODULE 1 | WEEK 3​

Chapter 3: Functions, Data Structures and Strings

In this chapter we will learn to organize code. Functions let us reuse code, Data Structures (List, Tuple, Dictionary, Set) let us handle lots of data, and Strings let us work with text. At the end there is a way to practice on HackerRank .

3.1 Functions​

A function is a named piece of code that does one specific job. Write it once, use it as many times as you like.

def greet(name): # created the function (define)
print(f"Hello, {name}!")
greet("Ali") # ran the function (call)
greet("Sara")

Parameters and Arguments​

  • Parameter: the name written in the brackets when creating the function ( name ).

  • Argument: the actual value given when running the function ( "Ali" ).

return vs print​

print() only shows something on the screen. return sends a value back that we can use further. This difference is very important.

def add(a, b):
return a + b
result = add(5, 3) # result now holds 8
print(result * 2) # 16, because we got a value from return
def add_print(a, b):
print(a + b) # only displays
x = add_print(5, 3) # 8 appeared on the screen
print(x) # None, because there was no return

Default and Keyword Arguments​

def power(base, exp=2): # exp has a default value of 2
return base ** exp
print(power(5)) # 25 (exp = 2)
print(power(2, 3)) # 8
print(power(exp=4, base=2)) # 16 (values given by name)

***args and kwargs (any number of arguments)

def total(*numbers): # becomes a tuple
return sum(numbers)
print(total(1, 2, 3, 4)) # 10
def show_info(**details): # becomes a dictionary
for key, value in details.items():
print(key, ":", value)
show_info(name="Ali", city="Karachi", age=21)

Docstring​

It is good practice to write a short explanation in triple quotes as the very first thing inside a function.

def area_of_circle(r):
"""Returns the area of a circle."""
return 3.14159 * r * r
print(area_of_circle(5))

lambda function (a small function)​

A one-line function with no name. For small jobs.

square = lambda x: x * x
print(square(6)) # 36
nums = [1, 2, 3, 4]
print(list(map(lambda x: x * 2, nums))) # [2, 4, 6, 8]

Recursion (a function calling itself)​

def factorial(n):
if n == 0 or n == 1: # the condition to stop (base case)
return 1
return n * factorial(n - 1)
print(factorial(5)) # 120

3.2 Scope (how far a variable can be seen)​

Scope means in which part of the code a variable can be used.

x = 10 # global variable
def show():
y = 5 # local variable (only inside the function)
print(x, y) # x is global, visible inside as well
show()
# print(y) # ERROR: y exists only inside the function

global keyword​

counter = 0
def increase():
global counter # say that we want to change the outside counter
counter += 1
increase()
increase()
print(counter) # 2

LEGB Rule​

Python looks for a variable in this order:

  1. L (Local): inside the function.

  2. E (Enclosing): inside the outer function (when there is a function inside a function).

  3. G (Global): in the whole file/program.

  4. B (Built-in): Python's own names such as print, len .

3.3 Lists​

A list is a way of keeping many values in one place, in order . It is written in [ ] . A list is mutable (that is, it can be changed after it is created).

fruits = ["apple", "mango", "banana"]
numbers = [10, 20, 30, 40, 50]
mixed = [1, "Ali", 3.5, True] # it can hold different types too
print(len(fruits)) # 3

Index (position)​

The index starts from 0 . Counting from the end uses -1 , -2 .

nums = [10, 20, 30, 40, 50]
print(nums[0]) # 10 (first)
print(nums[2]) # 30
print(nums[-1]) # 50 (last)
print(nums[-2]) # 40
nums[1] = 99 # we can change it
print(nums) # [10, 99, 30, 40, 50]

Slicing: list[start:stop:step]​

nums = [0, 10, 20, 30, 40, 50]
print(nums[1:4]) # [10, 20, 30] (stop not included)
print(nums[:3]) # [0, 10, 20]
print(nums[3:]) # [30, 40, 50]
print(nums[::2]) # [0, 20, 40]
print(nums[::-1]) # [50, 40, 30, 20, 10, 0] (reversed)

Important List Methods​

MethodWorkExample
append(x)Add at the endlst.append(5)
insert(i, x)Add at index ilst.insert(1, 99)
extend(list2)Join another listlst.extend([7, 8])
remove(x)Remove the first xlst.remove(5)
pop(i)Take out the item at index i and return it (last by default)lst.pop()
sort()Put in orderlst.sort()
reverse()Reverse itlst.reverse()
count(x)How many times x occurslst.count(5)
index(x)Index of xlst.index(5)
len(lst)How many items there arelen(lst)
lst = [3, 1, 2]
lst.append(5) # [3, 1, 2, 5]
lst.insert(0, 9) # [9, 3, 1, 2, 5]
lst.remove(1) # [9, 3, 2, 5]
last = lst.pop() # 5 came out, lst = [9, 3, 2]
lst.sort() # [2, 3, 9]
print(lst, last)
print(sorted([5, 2, 8], reverse=True)) # [8, 5, 2]
print(max(lst), min(lst), sum(lst))

List Comprehension (a short way to build a list)​

squares = [x * x for x in range(1, 6)]
print(squares) # [1, 4, 9, 16, 25]
evens = [x for x in range(1, 11) if x % 2 == 0]
print(evens) # [2, 4, 6, 8, 10]

Nested Lists and the Copy Problem​

matrix = [[1, 2, 3], [4, 5, 6]]
print(matrix[1][2]) # 6 (second row, third column)
a = [1, 2, 3]
b = a # this is not a copy, it is a second name for the same list
b.append(4)
print(a) # [1, 2, 3, 4] a changed too!
c = a.copy() # a real copy
c.append(5)
print(a, c)

3.4 Tuples​

A tuple is just like a list, but immutable : once created it cannot be changed. It is written in ( ) .

ANALOGY / EXAMPLE

A list is a note written in pencil (you can erase it). A tuple is writing done in pen (you cannot change it). Like the date of birth on a CNIC, which does not change every day.

point = (10, 20)
colors = ("red", "green", "blue")
print(point[0]) # 10
# point[0] = 5 # ERROR: a tuple cannot be changed
single = (5,) # a comma is necessary in a one-item tuple
print(type(single))
x, y = point # unpacking
print(x, y)

When should we use a tuple? When the data should not change (coordinates, colours, fixed settings), or when a function has to return several values together.

def min_max(nums):
return min(nums), max(nums) # returns a tuple
lo, hi = min_max([4, 9, 1, 7])
print(lo, hi) # 1 9

3.5 Dictionaries​

A dictionary keeps data as key : value pairs. It is written in . To look up a value we use a key instead of an index.

student = {"name": "Ali", "age": 21, "city": "Karachi"}
print(student["name"]) # Ali
print(student.get("marks")) # None (no such key, but no error)
print(student.get("marks", 0)) # 0 (default value)
student["age"] = 22 # changing
student["marks"] = 85 # adding a new key
del student["city"] # removing
print(student)

Looping and Important Methods​

prices = {"apple": 120, "mango": 200, "banana": 60}
print(prices.keys()) # all keys
print(prices.values()) # all values
for fruit, price in prices.items():
print(fruit, "->", price)
print("mango" in prices) # True (key check)

Nested Dictionary and Dictionary Comprehension​

students = {
"ali": {"age": 21, "marks": 85},
"sara": {"age": 20, "marks": 92},
}
print(students["sara"]["marks"]) # 92
squares = {n: n * n for n in range(1, 5)}
print(squares) # {1: 1, 2: 4, 3: 9, 4: 16}

Example (word count): count how many times each word appears in a text, using a dictionary.

text = "data science data ai data"
counts = {}
for word in text.split():
counts[word] = counts.get(word, 0) + 1
print(counts) # {'data': 3, 'science': 1, 'ai': 1}

3.6 Sets​

A set is a collection in which each item appears only once (duplicates are removed automatically) and there is no order (index). It is also written in .

nums = {1, 2, 2, 3, 3, 3}
print(nums) # {1, 2, 3}
data = [1, 2, 2, 3, 3, 4]
unique = list(set(data)) # the easiest way to remove duplicates
print(unique)
s = {1, 2}
s.add(3)
s.remove(1) # gives an error if not found; discard() does not
print(s)

Set Operations (the Venn diagram operations)

a = {1, 2, 3, 4}
b = {3, 4, 5, 6}
print(a | b) # union: {1, 2, 3, 4, 5, 6} everything combined
print(a & b) # intersection: {3, 4} common to both
print(a - b) # difference: {1, 2} in a, not in b
print(a ^ b) # symmetric: {1, 2, 5, 6} everything except the common part

Comparing the Four​

FeatureList [ ]Tuple ( )Dictionary { k:v }Set { }
OrderYesYesYes (insertion order)No
Can be changed (mutable)YesNoYesYes
DuplicatesAllowedAllowedKeys uniqueNo
Access by indexYesYesBy keyNo
FeatureList [ ]Tuple ( )Dictionary { k:v }Set { }
When to useOrdered data that
changes
Fixed dataLooking up data by nameUnique items, set math

3.7 String Manipulation​

A string is text. Python makes it easy to do a lot of work on strings. Every character of a string can be reached by index, but a string is immutable (you cannot directly change one character).

s = "Data Science"
print(s[0]) # D
print(s[-1]) # e
print(s[0:4]) # Data
print(s[::-1]) # ecneicS ataD (reversed)
print(len(s)) # 12
# s[0] = "d" # ERROR: a string cannot be changed

Important String Methods​

MethodWorkExample and result
upper() / lower()Capital / small letters"ali".upper() = "ALI"
title()Capital first letter of every word"data science".title() = "Data Science"
strip()Remove empty space at the start and end" hi ".strip() = "hi"
split()Break text into pieces (a list is made)"a b c".split() = ["a","b","c"]
join()Join a list into text"-".join(["a","b"]) = "a-b"
replace(a, b)Replace a with b"cat".replace("c","b") = "bat"
find(x)Position of x (-1 if not found)"hello".find("l") = 2
count(x)How many times x occurs"banana".count("a") = 3
startswith() / endswith()Check the start or end"file.csv".endswith(".csv") = True
isdigit() / isalpha()Only digits / only letters?"123".isdigit() = True
text = " Data Science is Fun "
t = text.strip()
print(t.upper())
print(t.lower())
print(t.split()) # ['Data', 'Science', 'is', 'Fun']
print("-".join(t.split())) # Data-Science-is-Fun
print(t.replace("Fun", "Great"))
print(t.count("a"), t.find("Science"))
print("123".isdigit(), "abc".isalpha())

Formatting and Special Characters​

name, marks = "Sara", 91.5
print(f"{name} got {marks} marks")
print(f"Pi = {3.14159:.2f}") # up to 2 decimals: 3.14
print("First line\nSecond line") # \n = new line
print("Name:\tAli") # \t = tab (empty space)

Famous String Examples​

# Palindrome (reads the same forwards and backwards)
word = "madam"
print(word == word[::-1]) # True
# Count vowels
text = "Machine Learning"
vowels = 0
for ch in text.lower():
if ch in "aeiou":
vowels += 1
print("Vowels:", vowels)
# Capitalize the first letter of every word
print("python is easy".title())
COMMON MISTAKES​
  • Copying a list with b = a . For a real copy write a.copy() .

  • Trying to change a tuple or a string. They are immutable.

  • Asking for a key that does not exist with d["x"] (KeyError). Use d.get("x") .

  • Thinking is an empty set. It is an empty dictionary.

  • Writing print in a function and thinking it returns the value. You need return to send it back.

  • Thinking the index starts at 1. In Python the index starts at 0 .

3.8 Hackerrank Practice​

HackerRank is a website with coding problems where your code is checked instantly. It builds the habit of problem solving, and also prepares you for interviews.

How to Get Started​

  1. Make a free account at hackerrank.com .

  2. In the Prepare section, choose the Python track.

  3. Start with the easiest problems ( Easy ).

  4. Try on your own first, for at least 20 to 30 minutes. Only then look at a hint or the discussion.

  5. Solve 1 to 2 problems every day; a little every day is better than a lot once a week.

  6. After solving, also read other people's solutions; you learn new approaches.

Problems for These Topics (for this chapter)​

TopicProblem names (HackerRank Python track)
Basics, if-elseSay "Hello, World!" With Python, Python If-Else, Arithmetic Operators, Python: Division, Loops
FunctionsWrite a function, Print Function
ListsList Comprehensions, Find the Runner-Up Score!, Nested Lists, Lists
Tuples and DictionariesTuples, Finding the percentage
StringssWAP cASE, String Split and Join, What's Your Name?, Mutations, Find a string, Capitalize!
KEY TAKEAWAYS​
  • Function = a reusable piece of code. print displays, return sends back.

  • Scope: local only inside the function, global in the whole program. Python searches in the LEGB order.

  • List: ordered and changeable. Tuple: ordered but not changeable.

  • Dictionary: finding a value by key. Set: only unique items, plus union, intersection, difference.

  • Index starts at 0. Slicing is [start:stop:step], and stop is not included.

  • Strings have many methods (upper, lower, strip, split, join, replace, find, count).

  • Practice a little on HackerRank every day, and try on your own first.