Fundamentals 11 min read

Python Data Structures: Strings, Lists, Tuples, Dicts & Sets

This guide walks through Python’s core data structures—strings, lists, tuples, dictionaries, and sets—detailing their creation, common built‑in methods, slicing, updating, and iteration with clear code examples, helping readers master essential operations for effective data manipulation.

MaGe Linux Operations
MaGe Linux Operations
MaGe Linux Operations
Python Data Structures: Strings, Lists, Tuples, Dicts & Sets

1. Strings

Demonstrates creating a string variable and using common string methods such as capitalize(), count(), center(), endswith(), isdigit(), join(), strip(), split(), and formatted output with format().

name = 'derek'
print(name.capitalize())          # Derek
print(name.count("e"))            # 2
print(name.center(10, '*'))       # **derek***
print(name.endswith("k"))         # True
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']
msg = 'my name is {name} and i am {age} old'
print(msg.format(name='derek', age=20))  # my name is derek and i am 20 old

Common built‑in string methods are listed with brief explanations:

# 1  string.capitalize()          # first character uppercase
# 2  string.center(width)         # center string, pad with spaces
# 3  string.count(sub, beg=0, end=len(string))  # count occurrences
# 4  string.decode(encoding='UTF-8', errors='strict')
# 5  string.encode(encoding='UTF-8', errors='strict')
# 6  string.endswith(suffix, beg=0, end=len(string))
# 7  string.expandtabs(tabsize=8)
# 8  string.find(sub, beg=0, end=len(string))
# 9  string.index(sub, beg=0, end=len(string))
#10  string.isalnum()
#11  string.isalpha()
#12  string.isdecimal()
#13  string.isdigit()
#14  string.islower()
#15  string.isnumeric()
#16  string.isspace()
#17  string.istitle()
#18  string.isupper()
#19  string.join(iterable)
#20  string.ljust(width)
#21  string.lower()
#22  string.lstrip()
#23  string.maketrans(intab, outtab)
#24  max(string)
#25  min(string)
#26  string.partition(sep)
#27  string.replace(old, new, num=string.count(old))
#28  string.rfind(sub, beg=0, end=len(string))
#29  string.rindex(sub, beg=0, end=len(string))
#30  string.rjust(width)
#31  string.rpartition(sep)
#32  string.rstrip()
#33  string.split(sep="", num=string.count(sep))
#34  string.splitlines(num=string.count('
'))
#35  string.startswith(prefix, beg=0, end=len(string))
#36  string.strip([chars])
#37  string.swapcase()
#38  string.title()
#39  string.translate(table, del="")
#40  string.upper()

2. Lists

Shows how to create a list, access elements by index or slice, and perform common operations such as append(), remove(), pop(), del, insert(), extend(), count(), sort(), reverse(), index(), and iteration with enumerate().

# create list
fruit = ['apple', 'pear', 'grape', 'orange']
print(fruit[1])          # pear
print(fruit[1:3])        # ['pear', 'grape']
print(fruit[-1])         # orange
print(fruit[:2])         # ['apple', 'pear']
# append
fruit.append('peach')
print(fruit)
# remove
fruit.remove('peach')
print(fruit)
# pop last element
fruit.pop()
print(fruit)
# delete by index
del fruit[2]
print(fruit)
# insert at index 1
fruit.insert(1, 'grape')
print(fruit)
# modify element
fruit[2] = 'orange'
print(fruit)
# extend with another list
fruit1 = ['apple', 'orange']
fruit2 = ['pear', 'grape']
fruit1.extend(fruit2)
print(fruit1)
# count occurrences
print(fruit1.count('apple'))
# sort and reverse
fruit1.sort()
print(fruit1)
fruit1.reverse()
print(fruit1)
# get index
print(fruit1.index('apple'))
# enumerate
for idx, item in enumerate(fruit1):
    print(idx, item)

3. Tuples

Illustrates tuple creation and two useful methods: count() and index().

fruit = ('apple', 'orange', 'grape')
print(fruit.count('apple'))   # 1
print(fruit.index('orange'))  # 1

4. Dictionaries

Demonstrates creating a dictionary, adding and modifying key‑value pairs, deleting entries with pop(), retrieving values with get(), and iterating over keys, values, or items.

# create
dict_fruit = {1: 'apple', 2: 'orange', 3: 'grape'}
print(dict_fruit)
# add
dict_fruit[4] = 'pear'
print(dict_fruit)
# modify
dict_fruit[4] = 'peach'
print(dict_fruit)
# delete
dict_fruit.pop(4)
print(dict_fruit)
# get value
print(dict_fruit.get(1))
# iterate
for k, v in dict_fruit.items():
    print(k, v)
for k in dict_fruit.keys():
    print(k)
for v in dict_fruit.values():
    print(v)

5. Sets

Shows how to create a set, add single or multiple elements, remove elements, and perform set operations such as union, difference, and intersection.

# create
fruit = set(['apple', 'orange', 'pear'])
print(fruit)
# add single element
fruit.add('grape')
print(fruit)
# add multiple elements
fruit.update(['peach', 'banana'])
print(fruit)
# remove specific element
fruit.remove('banana')
print(fruit)
# pop random element
fruit.pop()
print(fruit)
# set operations
num1 = set([11, 22, 33, 44])
num2 = set([33, 44, 55, 66])
print(num1.union(num2))        # {11, 22, 33, 44, 55, 66}
print(num1.difference(num2))   # {11, 22}
print(num1.intersection(num2)) # {33, 44}
Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

PythonData StructuresSetsTutorialListsStringsDictionaries
MaGe Linux Operations
Written by

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.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.