Master Python’s Core Data Structures: Strings, Lists, Tuples, Dictionaries & Sets
This tutorial walks through Python’s most frequently used data structures—strings, lists, tuples, dictionaries, and sets—showing how to create them, perform common operations such as slicing, searching, adding, removing, and iterating, and illustrating each step with clear code examples.
1. Strings
Python strings provide many built‑in methods for manipulation, such as capitalizing, counting characters, centering, checking suffixes, testing digit content, joining, stripping, splitting, and more.
name = 'derek'
print(name.capitalize()) # Derek
print(name.count("e")) # 2
print(name.center(10, '*')) # ***derek***
print(name.endswith('k')) # False
print('244'.isdigit()) # True
print('+'.join(['1','2','3'])) # 1+2+3
print('
123'.strip()) # 123
print('1+2+3+4'.split('+')) # ['1', '2', '3', '4']String formatting can be done with format:
msg = 'my name is {name} and i am {age} old'
print(msg.format(name='derek', age=20))
# Output: my name is derek and i am 20 oldCommon built‑in methods include:
string.capitalize() # first character uppercase
string.center(width) # center with spaces
string.count(sub, beg=0, end=len(string))
string.decode(encoding='UTF-8', errors='strict')
string.encode(encoding='UTF-8', errors='strict')
string.endswith(suffix, beg=0, end=len(string))
string.expandtabs(tabsize=8)
string.find(sub, beg=0, end=len(string))
string.index(sub, beg=0, end=len(string))
string.isalnum()
string.isalpha()
string.isdecimal()
string.isdigit()
string.islower()
string.isnumeric()
string.isspace()
string.istitle()
string.isupper()
string.join(seq)
string.ljust(width)
string.lower()
string.lstrip()
string.maketrans(intab, outtab)
string.max()
string.min()
string.partition(sep)
string.replace(old, new, num=string.count(old))
string.rfind(sub, beg=0, end=len(string))
string.rindex(sub, beg=0, end=len(string))
string.rjust(width)
string.rpartition(sep)
string.rstrip()
string.split(sep="", num=string.count(sep))
string.splitlines(num=string.count('
'))
string.startswith(prefix, beg=0, end=len(string))
string.strip([chars])
string.swapcase()
string.title()
string.translate(table, del="")
string.upper()2. Lists
Lists are mutable sequences that support indexing, slicing, and a rich set of methods for modification.
# Create a list
fruit = ['apple', 'pear', 'grape', 'orange']
# Indexing and slicing
print(fruit[1]) # pear
print(fruit[1:3]) # ['pear', 'grape']
print(fruit[-1]) # orange
print(fruit[:2]) # ['apple', 'pear']
# Append and remove
fruit.append('peach')
print(fruit) # ['apple', 'pear', 'grape', 'orange', 'peach']
fruit.remove('peach')
print(fruit) # ['apple', 'pear', 'grape', 'orange']
# Pop and delete by index
fruit.pop() # removes 'orange'
print(fruit) # ['apple', 'pear', 'grape']
del fruit[2]
print(fruit) # ['apple', 'pear']
# Insert and modify
fruit.insert(1, 'grape')
print(fruit) # ['apple', 'grape', 'pear']
fruit[2] = 'orange'
print(fruit) # ['apple', 'grape', 'orange']
# Extend, count, sort, reverse, index
fruit1 = ['apple', 'orange']
fruit2 = ['pear', 'grape']
fruit1.extend(fruit2)
print(fruit1) # ['apple', 'orange', 'pear', 'grape']
print(fruit1.count('apple')) # 1
fruit1.sort()
print(fruit1) # ['apple', 'grape', 'orange', 'pear']
fruit1.reverse()
print(fruit1) # ['pear', 'orange', 'grape', 'apple']
print(fruit1.index('apple')) # 3
# Enumerate
for idx, item in enumerate(fruit1):
print(idx, item)
# 0 pear
# 1 orange
# 2 grape
# 3 apple3. Tuples
Tuples are immutable sequences.
# Create a tuple
fruit = ('apple', 'orange', 'grape')
print(fruit.count('apple')) # 1
print(fruit.index('orange')) # 14. Dictionaries
Dictionaries map keys to values and support dynamic insertion, modification, and deletion.
# Create a dictionary
fruit = {1: 'apple', 2: 'orange', 3: 'grape'}
print(fruit)
# Add a new key
fruit[4] = 'pear'
print(fruit)
# Modify a value
fruit[4] = 'peach'
print(fruit)
# Delete a key
fruit.pop(4)
print(fruit)
# Retrieve a value safely
print(fruit.get(1)) # apple
# Iterate over items, keys, values
for k, v in fruit.items():
print(k, v)
for k in fruit.keys():
print(k)
for v in fruit.values():
print(v)5. Sets
Sets store unordered unique elements and support mathematical operations.
# Create a set
fruit = set(['apple', 'orange', 'pear'])
print(fruit) # {'orange', 'pear', 'apple'}
# Add single element and multiple elements
fruit.add('grape')
fruit.update(['peach', 'banana'])
print(fruit)
# Remove elements
fruit.remove('banana')
fruit.pop() # removes an arbitrary element
print(fruit)
# Set operations
num1 = set([11, 22, 33, 44])
num2 = set([33, 44, 55, 66])
print(num1.union(num2)) # {66, 11, 22, 33, 44, 55}
print(num1.difference(num2)) # {11, 22}
print(num1.intersection(num2)) # {33, 44}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.
MaGe Linux Operations
Founded in 2009, MaGe Education is a top Chinese high‑end IT training brand. Its graduates earn 12K+ RMB salaries, and the school has trained tens of thousands of students. It offers high‑pay courses in Linux cloud operations, Python full‑stack, automation, data analysis, AI, and Go high‑concurrency architecture. Thanks to quality courses and a solid reputation, it has talent partnerships with numerous internet firms.
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.
