Python Fundamentals: String, List, Dictionary Operations and Common Techniques
This article provides a comprehensive Python tutorial covering essential string manipulations, list and dictionary operations, file handling, exception handling, performance measurement, and classic algorithmic examples such as palindrome checking, prime testing, and Fibonacci generation, each illustrated with clear code snippets.
1. String reversal – Use slicing or reduce to reverse a string.
# Using slicing to reverse a string
original_str = "hello"
reversed_str = original_str[::-1]
print("Reversed string:", reversed_str) # Output: olleh
# Using reduce to reverse a string
from functools import reduce
reversed_str = reduce(lambda x, y: y + x, original_str)
print("Reversed string:", reversed_str) # Output: olleh2. Palindrome check – Compare a string with its reversed version.
def is_palindrome(s):
return s == s[::-1]
test_str = "madam"
if is_palindrome(test_str):
print(f"{test_str} is a palindrome.")
else:
print(f"{test_str} is not a palindrome.")3. Word case transformations – capitalize(), title(), and upper() methods.
original_str = "hello world"
capitalized_str = original_str.capitalize()
print("Capitalize:", capitalized_str) # Hello world
title_str = original_str.title()
print("Title:", title_str) # Hello World
upper_str = original_str.upper()
print("Upper:", upper_str) # HELLO WORLD4. Splitting and stripping strings – split() returns a list; strip() removes surrounding whitespace.
sentence = "hello world this is python"
words = sentence.split()
print("Words:", words)
trimmed_str = " hello world ".strip()
print("Trimmed:", trimmed_str)5. Joining a list of strings – Use " ".join(list).
words = ["hello", "world", "this", "is", "python"]
sentence = " ".join(words)
print("Joined:", sentence)6. Finding unique elements – Convert to set for strings or lists.
unique_chars = set("hello")
print("Unique chars:", unique_chars)
unique_items = set([1, 2, 2, 3, 4, 4, 5])
print("Unique items:", unique_items)7. Repeating elements – List multiplication or addition.
# Multiplication
repeated_list = [1, 2] * 3
print("Repeated:", repeated_list)
# Addition
repeated_list = [1, 2] + [1, 2] + [1, 2]
print("Repeated:", repeated_list)8. List comprehensions and flattening – Generate new lists or flatten nested lists.
# Generate squares
squares = [x ** 2 for x in range(5)]
print("Squares:", squares)
# Flatten nested list
nested_list = [[1, 2], [3, 4], [5, 6]]
flattened = [item for sublist in nested_list for item in sublist]
print("Flattened:", flattened)9. Deep flattening – Use iteration_utilities.deepflatten or a recursive function.
from iteration_utilities import deepflatten
nested = [1, [2, [3, 4], 5], 6]
flattened = list(deepflatten(nested))
print("Deep flattened:", flattened)
def flatten(lst):
result = []
for item in lst:
if isinstance(item, list):
result.extend(flatten(item))
else:
result.append(item)
return result
print("Recursive flatten:", flatten(nested))10. Variable swapping – Tuple unpacking or a temporary variable.
# Direct swap
a, b = 5, 10
a, b = b, a
print("Swapped:", a, b)
# Using temp variable
temp = a
a = b
b = temp
print("Swapped with temp:", a, b)11. Enumerate index‑value pairs – enumerate() over an iterable.
fruits = ["apple", "banana", "cherry"]
for index, fruit in enumerate(fruits):
print(f"Index: {index}, Fruit: {fruit}")12. Measuring execution time – Use time.time() before and after code.
import time
start = time.time()
# Core code
time.sleep(2)
end = time.time()
print("Execution time:", end - start, "seconds")13. Checking object memory size – sys.getsizeof().
import sys
print("Int size:", sys.getsizeof(10))
print("String size:", sys.getsizeof("hello"))
print("List size:", sys.getsizeof([1,2,3]))14. Merging dictionaries – Dictionary unpacking or update().
# Unpacking merge
merged = {**{'a':1,'b':2}, **{'b':3,'c':4}}
print("Merged:", merged)
# Using update
d1 = {'a':1,'b':2}
d2 = {'b':3,'c':4}
d1.update(d2)
print("Updated:", d1)15. Random sampling – random.sample() selects unique elements.
import random
items = list(range(1,11))
sample = random.sample(items, 5)
print("Sampled:", sample)16. Checking list uniqueness – Compare length with set() length.
items = [1,2,3,4,5]
print("Unique?", len(items) == len(set(items)))17. Fibonacci sequence – Generator function using yield.
def fibonacci(n):
a, b = 0, 1
while a < n:
yield a
a, b = b, a + b
for num in fibonacci(10):
print(num)18. List average – sum() divided by len().
numbers = [1,2,3,4,5]
avg = sum(numbers) / len(numbers)
print("Average:", avg)19. Prime number test – Check divisibility up to square root.
def is_prime(n):
if n <= 1:
return False
for i in range(2, int(n**0.5)+1):
if n % i == 0:
return False
return True
print(is_prime(17))20. Character frequency – collections.Counter counts occurrences.
from collections import Counter
text = "hello world"
print(Counter(text))21. List intersection – Use set & to find common elements.
list1 = [1,2,3,4,5]
list2 = [4,5,6,7,8]
common = set(list1) & set(list2)
print("Common:", common)22. Sorting a dictionary by value – sorted() with lambda.
scores = {'Alice':95,'Bob':85,'Charlie':90}
sorted_scores = sorted(scores.items(), key=lambda x: x[1], reverse=True)
print(sorted_scores)23. Deleting a key from a dictionary – pop() or del.
scores = {'Alice':95,'Bob':85,'Charlie':90}
removed = scores.pop('Bob')
print(scores, removed)
del scores['Charlie']
print(scores)24. File existence check – os.path.exists().
import os
if os.path.exists('example.txt'):
print('File exists')
else:
print('File does not exist')25. Reading a file line by line – with open() and iteration.
with open('example.txt', 'r', encoding='utf-8') as f:
for line in f:
print('Line:', line.strip())26. Converting list elements to a string – map(str, list) and join().
numbers = [1,2,3,4,5]
joined = ", ".join(map(str, numbers))
print(joined)The article concludes that mastering these core Python syntax details—from basic string, list, and dictionary operations to exception handling, timing, memory inspection, generators, and file I/O—significantly boosts programming efficiency and code readability.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
