Data Structures and Strings Examples

Work with Python’s core data types—strings, lists, dictionaries, sets. Explore slicing, sorting, palindrome checks, punctuation removal, and common string utilities to write readable, maintainable code.

Python Program to Flatten a Nested List

Flattens nested lists.

nested = [[1,2],[3,4],[5]]
flat = [x for sub in nested for x in sub]
print(flat)

Output

[1, 2, 3, 4, 5]

Python Variables and Types

Define variables of different types and print them.

x = 42
name = "Alice"
pi = 3.14
is_valid = True
print(x, name, pi, is_valid)

Output

42 Alice 3.14 True

Python Strings Basics

Concatenate, format, and slice strings.

s = "Hello, Python"
print(s.lower())
print(s.upper())
print(s[0:5])
print(f"Length: {len(s)}")

Output

hello, python
HELLO, PYTHON
Hello
Length: 13

Python Lists and Loops

Iterate over lists and apply operations.

nums = [1, 2, 3, 4]
total = 0
for n in nums:
    total += n
print(total)
print([n * n for n in nums])

Output

10
[1, 4, 9, 16]

Python Dictionaries

Store key-value pairs and access values.

user = {"id": 1, "name": "Sam"}
print(user["name"]) 
user["role"] = "admin"
print(list(user.keys()))

Output

Sam
['id', 'name', 'role']

Python Program to Check Whether a String is Palindrome or Not

Checks reversed equality.

s = 'madam'
print(s == s[::-1])

Output

True

Python Program to Remove Punctuations From a String

Filters punctuation.

import string
s = "Hello, world!"
print(''.join(ch for ch in s if ch not in string.punctuation))

Output

Hello world

Python Program to Sort Words in Alphabetic Order

Sorts words.

s = "banana apple cherry"
print(' '.join(sorted(s.split())))

Output

apple banana cherry

Python Program to Illustrate Different Set Operations

Union and intersection.

A = {1,2,3}
B = {3,4}
print(A | B)
print(A & B)

Output

{1, 2, 3, 4}
{3}

Python Program to Slice Lists

Demonstrates slicing.

lst = [0,1,2,3,4,5]
print(lst[1:4])
print(lst[-3:])

Output

[1, 2, 3]
[3, 4, 5]

Python Program to Iterate Over Dictionaries Using for Loop

Iterates items.

d = {'a':1,'b':2}
for k, v in d.items():
    print(k, v)

Output

a 1
b 2

Python Program to Sort a Dictionary by Value

Sorts by values.

d = {'a':3,'b':1,'c':2}
print(dict(sorted(d.items(), key=lambda kv: kv[1])))

Output

{'b': 1, 'c': 2, 'a': 3}

Python Program to Check If a List is Empty

Truthiness check.

lst = []
print('Empty' if not lst else 'Not Empty')

Output

Empty

Python Program to Concatenate Two Lists

Uses + operator.

print([1,2] + [3,4])

Output

[1, 2, 3, 4]

Python Program to Print Colored Text to the Terminal

ANSI escape codes.

print('\x1b[31mRed\x1b[0m')

Output

Red

Python Program to Convert String to Datetime

Uses datetime.strptime.

from datetime import datetime
dt = datetime.strptime('2025-11-14', '%Y-%m-%d')
print(dt.year, dt.month, dt.day)

Output

2025 11 14

Python Program to Get a Substring of a String

Uses slicing.

s = 'abcdef'
print(s[1:4])

Output

bcd

Python Program to Create a Long Multiline String

Triple quotes.

s = '''line1
line2
line3'''
print(s)

Output

line1
line2
line3

Python Program to Count the Number of Occurrence of a Character in String

Uses str.count.

print('banana'.count('a'))

Output

3

Python Program to Find the Square Root

Computes square root using math module.

import math
print(math.sqrt(16))

Output

4.0

Keep Practicing

Use the online Python compiler to run examples and test variations. Reinforce learning by building small scripts for each topic.

FAQ

You can use the online Python compiler linked above to run examples instantly. For larger projects, install Python locally.

Yes. Examples cover variables, control flow, data structures, functions, classes, and file I/O—ideal for beginners.

Yes. The programs are tested and produce consistent output across major platforms.

Learn Python by Practicing Examples

Hands-on practice is the fastest way to understand Python. Each example focuses on a single concept—from variables, strings, lists, and dictionaries to loops, functions, classes, exceptions, and file I/O. Modify examples, add new functions, and see how clean design leads to readable, maintainable code.

Use our tools to deepen learning: the Python Compiler to run snippets, and the Python Tutorial for structured lessons.

Beginner-Friendly

Start with variables, operators, and control flow. Build confidence with small, readable programs.

Practical Patterns

Practice lists, dicts, comprehensions, functions, classes, exceptions, and file handling.

Grow Skills

Explore generators and decorators to write expressive, reusable code.