Bioinfo Lab

Bioinformatics Laboratory at BiUH.

Core Values: Respect, Reflection, Communication, Commitment.

Main Page   |   Util & Src   |   Contact


Loading......

Password


Content:

Section 1. Lists

Section 2. Tuples

Section 3. Dictionaries

Section 4. Sets

Section 5. Data Structures in Action


 

Section 1. Lists

← Prev | Home | Next →
 


1.1. What is a List?

Like a shopping list that can hold multiple items

# Shopping list example
groceries = ["apples", "milk", "eggs", "bread"]
print("My shopping list:" + str(groceries))

← Prev | Home | Next →
 


1.2. Four Ways to Create Lists

  1. Square brackets []
colors = ["red", "green", "blue"]
  1. list() constructor
numbers = list((1, 2, 3))  # Converts tuple to list

← Prev | Home | Next →
 


1.3. More Creation Methods

  1. List comprehension
squares = [x**2 for x in range(5)]
# [0, 1, 4, 9, 16]
  1. Convert from string
word = list("hello")
# ['h', 'e', 'l', 'l', 'o']

← Prev | Home | Next →
 


1.4. Accessing Elements

Positive indexing:

games = ["Mario", "Zelda", "Pokémon"]
print(games[0])  # Mario
print(games[-1]) # Pokémon (negative index)

← Prev | Home | Next →
 


1.5. Slicing Lists

Get sub-lists with [start:end]

months = ["Jan", "Feb", "Mar", "Apr", "May"]
print(months[1:3])  # ['Feb', 'Mar']
print(months[:2])   # First two: ['Jan', 'Feb']
print(months[3:])   # Last two: ['Apr', 'May']

← Prev | Home | Next →
 


1.6. Adding Items

append() and insert()

todo = ["wake up"]
todo.append("brush teeth")  # Add to end
todo.insert(1, "make bed")  # Insert at position 1
print(todo)  # ['wake up', 'make bed', 'brush teeth']


Q: todo.insert(0,’start’) ? todo.insert(len(todo),’end1’) ? todo.insert(-1,’end2’) ?



← Prev | Home | Next →
 


1.7. Removing Items

remove() and pop()

pets = ["cat", "dog", "hamster"]
pets.remove("dog")  # Remove by value
last = pets.pop()   # Remove last item
print(pets)         # ['cat']
print(last)         # 'hamster'


Q: pets=[“dog”, “bird”, “dog”, ‘cat’,”dog”]; pets.remove(“dog”) ?


Q: pets.index(‘dog’)?



← Prev | Home | Next →
 


1.8. Sorting Lists

sort() method

scores = [88, 92, 75, 100]
scores.sort()
print(scores)  # [75, 88, 92, 100]

# Reverse sort
scores.sort(reverse=True)
print(scores)  # [100, 92, 88, 75]

← Prev | Home | Next →
 


1.9. Practice: Student Grades System

Store multiple students’ scores

students = ["Alice", "Bob", "Charlie"]
scores = [88, 92, 75]

← Prev | Home | Next →
 


1.10. Calculate Average

total = sum(scores)
average = total / len(scores)
print("Class average: " + str(average))
# Output: Class average: 85.0


Q: how to convert the “+” to a f-string format (f””)?



← Prev | Home | Next →
 


1.11. Sort Scores

Combine data with zip()

combined = []
i=0
while i<len(scores):
    combined.append( [scores[i], students[i]] )
    i=i+1

combined.sort()

print("Ranking:")
for one in combined:
    print(str(one[1]) + ": " + str(one[0]))


Q: sort in reverse order?



← Prev | Home | Next →
 

Section 2. Tuples

← Prev | Home | Next →
 


2.1. Tuples vs Lists: Immutability Demo

# Lists are mutable
fruits = ["apple", "banana", "cherry"]
fruits[0] = "avocado"
print(fruits)  # Changes successfully

# Tuples are immutable (unchangeable)
colors = ("red", "green", "blue")


colors[0] = "pink"

# report error

Key difference: 📌 Tuples use () while lists use [] 📌 Tuple elements cannot be changed after creation


← Prev | Home | Next →
 


2.2. Why Immutability Matters?

Real-life examples of unchangeable data:

  • Geographic coordinates (latitude, longitude)
  • RGB color codes
  • Date components (year, month, day)
# Valid tuple usage
black = (0, 0, 0)
current_position = (37.7749, -122.4194)

← Prev | Home | Next →
 


2.3. Tuple Unpacking

Basic unpacking:

dimensions = (1920, 1080)
width, height = dimensions
print("Screen: " + str(width) + "x" + str(height))

Swapping variables:

a = 5
b = 10
a, b = b, a

← Prev | Home | Next →
 


2.4. Advanced Unpacking Tricks

Ignoring values:

coordinates = (45, -73, 100)
lat, lon, _ = coordinates

Multiple assignment:

# Get first and last items
numbers = (3, 1, 4, 1, 5, 9)
first, *middle, last = numbers


Q: what is the content of “middle” ?



← Prev | Home | Next →
 


2.5. Single-element Tuple Trap

Common mistake:

not_a_tuple = (42)
print(type(not_a_tuple))  # <class 'int'>

Correct way:

proper_tuple = (42,)
print(type(proper_tuple))  # <class 'tuple'>

Visual reminder: ❗ Always add comma for single items ❗


Q: proper_tuple[0] ? proper_tuple[1] ?



← Prev | Home | Next →
 


2.6. Returning Multiple Values

Simple example:

def circle_calc(radius):
    area = 3.14 * radius ** 2
    circumference = 2 * 3.14 * radius
    return (area, circumference)

results = circle_calc(5)
print("Area: " + str(results[0]) + ", Circumference: " + str(results[1]))

Better usage with unpacking:

area, circ = circle_calc(7)
print("Area is " + str(area) + " units")

← Prev | Home | Next →
 


2.7. When to Use Tuples?

Perfect for:

  1. Data that shouldn’t change (constants)
  2. Dictionary keys (unlike lists!)
  3. Function return values
  4. Protecting important data
# Valid dictionary key
locations = {
    (40.7128, -74.0060): "New York",
    (51.5074, -0.1278): "London"
}

← Prev | Home | Next →
 


2.8. Tuple Operations Summary

Essential methods:

my_tuple = (1, 2, 3)

print(len(my_tuple))      # 3
print(2 in my_tuple)      # True
print(my_tuple.index(2))  # 1
print(my_tuple.count(2))  # 1

Remember:

No append/remove/pop methods!


← Prev | Home | Next →
 

Section 3. Dictionaries

← Prev | Home | Next →
 


3.1. Phone Book Analogy 📞

# Think of dictionaries like phone contacts:
phone_book = {
    "Alice": "555-1234",
    "Bob": "555-5678",
    "Charlie": "555-9012"
}
print(phone_book["Alice"])  # Outputs: 555-1234

← Prev | Home | Next →
 


3.2. Three Ways to Create Dictionaries

Method 1: Curly Braces {}

student = {"name": "Emma", "age": 20, "major": "CS"}

Method 2: dict() Constructor

colors = dict(red="#FF0000", green="#00FF00")

Method 3: List of Tuples

weekdays = dict([(1, "Mon"), (2, "Tue"), (3, "Wed")])

← Prev | Home | Next →
 


3.3. Adding & Changing Entries

animal_sounds = {}
animal_sounds["dog"] = "Woof!"  # Add new entry
animal_sounds["cat"] = "Mew"    # Add another
animal_sounds["cat"] = "Meow"   # Update existing
print(animal_sounds)  # {'dog': 'Woof!', 'cat': 'Meow'}

← Prev | Home | Next →
 


3.4. Removing Entries

del animal_sounds["dog"]        # Delete entry
removed = animal_sounds.pop("cat")
print(removed)  # "Meow"
print(animal_sounds)  # Empty now

← Prev | Home | Next →
 


3.5. Safe Value Access with get()

grades = {"Math": 90, "Science": 85}
print(grades.get("History", "Subject not found"))
# Outputs: Subject not found

← Prev | Home | Next →
 


3.6. Building a Simple Translator

nano translator.py

translator = {
    "hello": "hola",
    "goodbye": "adiós",
    "thank you": "gracias"
}

word = input("Enter English word: ").lower()
translation = translator.get(word, "Translation not available")
print("Spanish: " + str(translation))

← Prev | Home | Next →
 


3.7. Handling Unknown Words

if translation == "Translation not available":
    print("Please check spelling!")
    print("Current dictionary words:" + str(list(translator.keys())))

← Prev | Home | Next →
 


3.8. Dictionary Methods Summary

my_dict = {"a": 1, "b": 2}
print(my_dict.keys())    # dict_keys(['a', 'b'])
print(my_dict.values())  # dict_values([1, 2])
print(my_dict.items())   # dict_items([('a', 1), ('b', 2)])

← Prev | Home | Next →
 


3.9. Real-World Example: Movie Ratings

nano movie_rating.py

movies = {
    "Moana": 7.5,
    "Toy Story": 8.6,
    "Frozen": 8.5
}

movie = input("Enter movie title: ")
print("Rating: " + str(movies.get(movie, "Not in database")) + "/10")

← Prev | Home | Next →
 


3.10. Dictionary Power Tips 💡

  1. Keys can be numbers/strings/tuples
  2. Values can be ANY data type
  3. Fast lookup speed
  4. Great for organizing related data
mixed_example = {
    1: "Number key",
    (2,3): "Tuple key",
    "list": ["can", "be", "value"]
}

← Prev | Home | Next →
 

Section 4. Sets

← Prev | Home | Next →
 


4.1. What Makes Sets Special?

  • Unique Elements: Automatically removes duplicates
  • Unordered: No index-based access
  • Mutable: Can add/remove elements
  • Math Operations: Built-in set operations

← Prev | Home | Next →
 


4.2. Automatic Deduplication Demo

# List vs Set comparison
fruits_list = ['apple', 'banana', 'apple', 'orange']
fruits_set = {'apple', 'banana', 'apple', 'orange'}

print("List: " + str(fruits_list))  # Keeps duplicates
print("Set: " + str(fruits_set))    # Auto-removes duplicates

← Prev | Home | Next →
 


4.3. Real-World Deduplication Example

# Removing duplicate votes
votes = ['Alice', 'Bob', 'Alice', 'Charlie', 'Bob']
unique_voters = set(votes)

print("Total votes: " + str(len(votes)))
print("Unique voters: " + str(len(unique_voters)))

← Prev | Home | Next →
 


4.4. Set Operations: Intersection

# Common elements in both sets
art_students = {'Tom', 'Alice', 'Bob', 'Eve'}
music_students = {'Alice', 'Eve', 'John'}

both = art_students & music_students
print("Students in both clubs: " + str(both))

← Prev | Home | Next →
 


4.5. Set Operations: Union

# Combine sets (no duplicates)
week1_customers = {'Alice', 'Bob'}
week2_customers = {'Bob', 'Charlie'}

all_customers = week1_customers | week2_customers
print("All customers: " + str(all_customers))

← Prev | Home | Next →
 


4.6. Set Operations: Difference

# Elements in first set not in second
available_colors = {'red', 'blue', 'green'}
used_colors = {'blue', 'yellow'}

remaining = available_colors - used_colors
print("Remaining colors: " + str(remaining))

← Prev | Home | Next →
 


4.7. Voting System Case Study

nano vote.py

# Counting unique votes
votes = []
while True:
    vote = input("Enter candidate name (or 'done'): ")
    if vote.lower() == 'done':
        break
    votes.append(vote)

unique_votes = set(votes)
print("Candidates: " + ', '.join(unique_votes))


Q: how can we get the number of votes? hint: use dict



← Prev | Home | Next →
 


4.8. Friend Finder System

# Finding common friends
alice_friends = {'Bob', 'Charlie', 'Diana'}
bob_friends = {'Charlie', 'Diana', 'Eve'}

common = alice_friends & bob_friends
print("Common friends: " + str(common))

# Adding new friend
alice_friends.add('Eve')
print("Updated friends: " + str(alice_friends))

← Prev | Home | Next →
 


4.9. Set Methods Cheat Sheet

Method Example Description
add() s.add('x') Add element
remove() s.remove('x') Remove element
clear() s.clear() Empty the set
copy() new_set = s.copy() Create duplicate

List also has “clear()” and “copy()”


← Prev | Home | Next →
 


4.10. Why Use Sets?

  1. Fast membership testing: 'a' in set
  2. Mathematical operations: Easy intersections/unions
  3. Data cleaning: Quick duplicate removal
  4. Relationship modeling: Social networks, groups


Q: write a program to get all unique letters in your name?



← Prev | Home | Next →
 

Section 5. Data Structures in Action

← Prev | Home | Next →
 


5.1. Student Information System Demo

0. A demo

a = []
def add():
    a.append(1)

add()
print(a)
a = set()
def add():
    a.add(1)

add()
print(a)
a = {}
def add():
    a[1]=1

add()
print(a)
a=0
def add():
    print(a)

add()
print(a)
a=0
def add():
    a=a+1

add()
print(a)


Q: What happended here ?

mutable variable: list, dict, set

Variable “assignment” and “modifying its contents” (mutable) are two different things!

Assignment = replacing the box → requires global

Modifying contents = changing what’s inside the box → no global needed



← Prev | Home | Next →
 


5.2. Storing Students

# Create empty list
students = []

# Create student dictionary
student1 = {
    "name": "Alice",
    "age": 20,
    "major": "Computer Science"
}
students.append(student1)

← Prev | Home | Next →
 


5.3. Adding Students

def add_student():
    name = input("Enter name: ")
    age = int(input("Enter age: "))
    major = input("Enter major: ")
    
    new_student = {
        "name": name,
        "age": age,
        "major": major
    }
    students.append(new_student)
    print("Student added!")

← Prev | Home | Next →
 


5.4. Sorting Students


Q: add two students, order students by age ?



← Prev | Home | Next →
 


5.5. Word Frequency Analyzer

1. Splitting Text

text = "apple banana orange apple pear orange apple ok yes yes ok no no want"
words = text.lower().split()

print(words)

← Prev | Home | Next →
 


5.6. Counting Words

word_counts = {}

for word in words:
    if word in word_counts:
        word_counts[word] += 1
    else:
        word_counts[word] = 1

print(word_counts)

← Prev | Home | Next →
 


5.7. Finding TOP5 Words


Q: How can we get top5 words?



← Prev | Home


End