DEV Community

abiud kipngetich
abiud kipngetich

Posted on

Python Data Structures, Strings, and File Handling


Enter fullscreen mode Exit fullscreen mode

1. Core Data Structures

Lists

Ordered, mutable collections that allow duplicates.
fruits = ["apple", "banana", "cherry"]

Slicing

Extract a sub-sequence using [start:stop:step]. Works on lists, strings, and tuples

numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
print(numbers[2:5])        # [2, 3, 4] 
print(numbers[:3])         # [0, 1, 2] 
print(numbers[7:])         # [7, 8, 9] 
print(numbers[::2])        # [0, 2, 4, 6, 8] 
print(numbers[::-1])       # reversed list
Enter fullscreen mode Exit fullscreen mode

Dictionaries

Unordered collection of key-value pairs. Keys must be unique and immutable.

person = {"name": "Alice", "age": 30} 
print(person["name"])                 # Alice 
print(person.get("email", "N/A"))     # safe lookup with default
Enter fullscreen mode Exit fullscreen mode

Tuples

Ordered, immutable collections. Once created, they can't be changed.

coordinates = (10.0, 20.0) 
x, y = coordinates       # unpacking
Enter fullscreen mode Exit fullscreen mode

Sets

Unordered collections of unique elements. No duplicates, no indexing.

unique_numbers = {1, 2, 2, 3, 3, 3} 
print(unique_numbers)      # {1, 2, 3}
Enter fullscreen mode Exit fullscreen mode

2. List Methods, Adding and Updating Values

nums = [1, 2, 3] 
nums.append(4)       # add to end -> [1, 2, 3, 4] 
nums.insert(0, 0)    # insert at index -> [0, 1, 2, 3, 4] 
nums.extend([5, 6])  # add multiple -> [0, 1, 2, 3, 4, 5, 6] 
nums.remove(3)       # remove by value 
popped = nums.pop()  # remove and return last item 
nums.sort()          # sort in place 
nums.reverse()       # reverse in place 

nums[0] = 99         # update by index
Enter fullscreen mode Exit fullscreen mode

Dictionaries update similarly:

person = {"name": "Alice"} 
person["age"] = 30               # add a new key 
person["name"] = "Jack"          # update existing key 
person.update({"city": "Nairobi", "age": 31})    # bulk update 
del person["city"]               # remove a key
Enter fullscreen mode Exit fullscreen mode

Use list for an ordered, changeable collection; a tuple for fixed data that shouldn't change (e.g., coordinates); a dictionary for labeled data accessed by key; a set when you need uniqueness or fast membership testing.

3. List Comprehension

A compact way to build a list from an iterable.

squares = [n ** 2 for n in range(10)] 
evens = [n for n in range(20) if n % 2 == 0] 
upper_names = [name.upper() for name in ["ana", "bo", "cy"]]
Enter fullscreen mode Exit fullscreen mode

Dictionary and set comprehensions work the same way:

square_map = {n: n ** 2 for n in range(5)} 
unique_lengths = {len(word) for word in ["hi", "bye", "ok"]} 
Enter fullscreen mode Exit fullscreen mode

4. Set Operations: Intersection, Union, and Unpacking

a = {1, 2, 3, 4} 
b = {3, 4, 5, 6} 

print(a | b)          # union: {1, 2, 3, 4, 5, 6}
print(a.union(b)) 

print(a & b)          # intersection: {3, 4} 
print(a.intersection(b)) 

print(a - b)          # difference: {1, 2} 
print(a ^ b)          # symmetric difference: {1, 2, 5, 6}
Enter fullscreen mode Exit fullscreen mode

Unpacking

Assigning multiple variables at once from an iterable, including with * to capture "the rest."

point = (1, 2, 3) 
x, y, z = point 

first, *middle, last = [1, 2, 3, 4, 5] 
print(first, middle, last)      # 1 [2, 3, 4] 5 

def add(a, b, c): 
    return a + b +c 

values = (1, 2, 3) 
print(add(*values))          # unpack tuple as arguments 

Enter fullscreen mode Exit fullscreen mode

5. isnumeric() and Type-Checking Functions

"123".isnumeric()         # True 
"12.5".isnumeric()        # False (decimal point isn't numeric) 
"abc".isnumeric()         # False 

"abc".isalpha()           # True, all are alphabetic characters 
"abc123".isalnum()        # True, letters and/or numbers only 
" ".isspace()             # True, all whitespace 
"Hello World".istitle()   # True, title-cased 
"HELLO".isupper()         # True 
"hello".islower()         # True
Enter fullscreen mode Exit fullscreen mode

These are commonly used to validate user input before conversion, e.g.,if
age_str.isnumeric(): age = int(age_str)
.

6. String Methods, Concatenation, and Repetition

greeting = "Hello" + " " + "Wendy"    # concatenation -> "Hello Wendy" 
laugh = "ha" * 3                  # repetition -> "hahaha" 

text = "Python is Fun" 
print(text.upper())               # PYTHON IS FUN 
print(text.lower())               # python is fun 
print(text.title())               # Python Is Fun 

Enter fullscreen mode Exit fullscreen mode

7. Standardizing Text

Before comparing or storing text, it's common to normalize its case and formatting so comparisons are consistent.

user_input = "  Hello WORLD " 
standardized = user_input.strip().lower() 
print(standardized)           # "hello world"
Enter fullscreen mode Exit fullscreen mode

8. Removing Extra Spaces: strip, lstrip, rstrip

text = "  padded text  " 
print(text.strip())         # "padded text" - removes both sides 
print(text.lstrip())        # "padded text "- removes left only 
print(text.rstrip())        # " padded text"- removes right only 

# _can also strip specific characters _
print("---data---".strip("-"))   # "data"
Enter fullscreen mode Exit fullscreen mode

9. Splitting Text Apart

.split() breaks a string into a list based on a separator.
.splitlines() breaks a multi-line string into a list of lines.

sentence = "the quick brown fox" 
words = sentence.split()          # ['the', 'quick', 'brown', 'fox'] 

csv_line = "a,b,c,d 
fields = csv_line.split(",")      # ['a', 'b', 'c', 'd'] 

paragraph = "line one\nline two\nline three" 
lines = paragraph.splitlines()    # ['line one', 'line two', 'line three']
Enter fullscreen mode Exit fullscreen mode

10. Putting Text Back Together: .join()

.join() is the inverse of .split(), it combines a list of strings using a separator string

words = ["the", "quick", "brown", "fox"] 
sentence = " ".join(words)     # "the quick brown fox" 

fields = ["a", "b", "c"] 
csv_line = ",".join(fields)    # "a,b,c" 

lines = ["line one", "line two"]
text_block = "\n".join(lines)
Enter fullscreen mode Exit fullscreen mode

11. Validation Methods: count, replace, and Checking Text Kind

text = "banana" 
print(text.count("a"))                # 3 

text2 = "I like dogs" 
print(text2.replace("dogs", "cats"))   # "I like cats" 

# checking kind of text (combines with isnumeric/isalpha etc.) 
def validate_username(name):
    if not name.isalnum(): 
        return "Username must be letters/numbers only" 
    return "Valid"
Enter fullscreen mode Exit fullscreen mode

12. Prefixes, Suffixes, and Professional Formatting

filename = "report_final.pdf 
print(filename.startswith("report"))   # True 
print(filename.endswith(".pdf"))       # True 
Enter fullscreen mode Exit fullscreen mode


plaintext

professional formatting example

name = "john thuto" 
formatted = name.title()             # "John Thuto" 

price = 1234.5 
print(f"ksh {price:,.2f})            # "Ksh 1,234.50"
Enter fullscreen mode Exit fullscreen mode


plaintext

13. File Handling

Opening and closing a file

file = open("data.txt", "r")    # modes: 'r' read, 'w' write, 'a' append, 'x' create 
content = file.read() 
file.close()       # must manually close to free the resource 
Enter fullscreen mode Exit fullscreen mode


plaintext
Forgetting to close a file can leak resources or leave writes unflushed, this is why the with statement is preferred.

The with statement

with automatically closes the file when the block ends, even if an error occurs.

with open("data.text", "r") as file: 
     content = file.read() 
# file is automatically closed here
Enter fullscreen mode Exit fullscreen mode


plaintext

Reading from a file

with open("data.txt", "r") as file: 
     content = file.read()           # entire file as one string 

with open("data.txt", "r") as file: 
    for line in file:                # iterate line by line 
        print(line.strip()) 

with open("data.txt", "r") as file: 
    lines = file.readlines()         # list of lines, icluding \n
Enter fullscreen mode Exit fullscreen mode


plaintext

Writing to a file

with open("output.txt"z, "w") as file: 
    file.write("Hello, World!\n") 

with open("output.txt", "a") as file:    # append mode adds without erasing 
    file.write("Another line.\n")
Enter fullscreen mode Exit fullscreen mode

Top comments (0)