Data Structures and Strings Examples

Key Takeaway: Practice Python with 110+ runnable examples covering strings, lists, dicts, math, dates, OOP, and file I/O — complete with expected terminal outputs.

Audience & Use Case: Designed for computer science students, data analysts, backend developers, and job seekers preparing for Python technical interviews.

Last updated: October 2026 110 Verified Examples

Quick Start & How to Use

  1. Select a Python example topic from the sidebar menu (or mobile dropdown).
  2. Examine the structured source code and corresponding expected output.
  3. Copy code directly or test it in our Online Python Compiler.
  4. Experiment by tweaking variables, loops, and conditions to deepen your understanding.

Who is this for: Beginners, interview candidates, and developers looking for reliable code snippets.

Credible Resources:Python Tutorial · Python Compiler · Python 3 Official Documentation · JavaScript Examples

Python Dictionaries

Store key-value pairs and access values.

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

Python Variables and Types

Define variables of different types and print them.

Source Code
x = 42
name = "Alice"
pi = 3.14
is_valid = True
print(x, name, pi, is_valid)
Expected Output
42 Alice 3.14 True

Python Strings Basics

Concatenate, format, and slice strings.

Source Code
s = "Hello, Python"
print(s.lower())
print(s.upper())
print(s[0:5])
print(f"Length: {len(s)}")
Expected Output
hello, python
HELLO, PYTHON
Hello
Length: 13

Python Lists and Loops

Iterate over lists and apply operations.

Source Code
nums = [1, 2, 3, 4]
total = 0
for n in nums:
    total += n
print(total)
print([n * n for n in nums])
Expected Output
10
[1, 4, 9, 16]

Python Program to Check Whether a String is Palindrome or Not

Checks reversed equality.

Source Code
s = 'madam'
print(s == s[::-1])
Expected Output
True

Python Program to Remove Punctuations From a String

Filters punctuation.

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

Python Program to Sort Words in Alphabetic Order

Sorts words.

Source Code
s = "banana apple cherry"
print(' '.join(sorted(s.split())))
Expected Output
apple banana cherry

Python Program to Illustrate Different Set Operations

Union and intersection.

Source Code
A = {1,2,3}
B = {3,4}
print(A | B)
print(A & B)
Expected Output
{1, 2, 3, 4}
{3}

Python Program to Flatten a Nested List

Flattens nested lists.

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

Python Program to Slice Lists

Demonstrates slicing.

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

Python Program to Iterate Over Dictionaries Using for Loop

Iterates items.

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

Python Program to Sort a Dictionary by Value

Sorts by values.

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

Python Program to Check If a List is Empty

Truthiness check.

Source Code
lst = []
print('Empty' if not lst else 'Not Empty')
Expected Output
Empty

Python Program to Concatenate Two Lists

Uses + operator.

Source Code
print([1,2] + [3,4])
Expected Output
[1, 2, 3, 4]

Python Program to Print Colored Text to the Terminal

ANSI escape codes.

Source Code
print('\x1b[31mRed\x1b[0m')
Expected Output
Red

Python Program to Convert String to Datetime

Uses datetime.strptime.

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

Python Program to Get a Substring of a String

Uses slicing.

Source Code
s = 'abcdef'
print(s[1:4])
Expected Output
bcd

Python Program to Create a Long Multiline String

Triple quotes.

Source Code
s = '''line1
line2
line3'''
print(s)
Expected Output
line1
line2
line3

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

Uses str.count.

Source Code
print('banana'.count('a'))
Expected Output
3

Python Program to Find the Square Root

Computes square root using math module.

Source Code
import math
print(math.sqrt(16))
Expected Output
4.0

Python Core Concepts & Decision Breakdown

CategoryCore ConceptsPrimary Use CaseOfficial Docs
Primitives & Basicsint, float, str, boolBasic arithmetic, logic checks, string formattingBuilt-in Types
Data Structureslist, tuple, dict, setCollections, lookup maps, data filteringData Structures
Control Flowif/else, for, while, try/exceptIteration, conditional execution, error handlingControl Flow
OOP & Modulardef, class, lambda, importObject orientation, modularization, reusabilityClasses & OOP

Keep Practicing

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

Frequently Asked Questions

Python is a high-level, interpreted programming language known for readable syntax. Practicing with runnable examples accelerates learning by reinforcing concepts through immediate feedback.

You can run all examples instantly using our integrated Online Python Compiler directly in your web browser without downloading any software.

Yes. The programs cover foundational topics including arithmetic, strings, lists, dictionaries, recursion, algorithms, and file operations commonly tested in coding interviews.

Yes. All snippets use standard Python 3 syntax and libraries, ensuring cross-platform compatibility across Windows, macOS, Linux, and web-based environments.

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, the Python Official Docs for language standards, 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.