Median of a list

Python Practice › List Programs › Program 100

Median of a list

EasyList Programs · 100 of 100

Write a Python program to get the median of all the elements of a list.

Input
[2, 4, 6, 7, 5, 8, 3, 11]
Output
[2, 3, 4, 5, 6, 7, 8, 11] 5.5 5.5

Approach

  1. Sort; for an even count average the two middle values.

Solution

Python
import statistics items = [2, 4, 6, 7, 5, 8, 3, 11]s = sorted(items)mid = len(s) // 2median = s[mid] if len(s) % 2 else (s[mid - 1] + s[mid]) / 2print(s, median, statistics.median(items))
Output
[2, 3, 4, 5, 6, 7, 8, 11] 5.5 5.5

Line by line

Line 5

Eight values, so the median is the average of the 4th and 5th sorted values, 5 and 6.

Learn the concept

New to this topic? Read the lesson, then come back.

More list programs

← All 100 List Programs

Python Introduction

Python Tutorial › Getting Started › Python Introduction

Python Introduction

BeginnerLesson 2 of 478 min read4 runnable examples

Python is a general-purpose programming language known for code that is short and easy to read. This lesson explains what Python is, why it is so popular, and what happens when you run a Python program.

In this lesson
  • What Python is and who made it
  • The features that make Python popular
  • Where Python is used
  • How the interpreter runs your code

What is Python?

Python is a high-level, interpreted, general-purpose programming language.

  • High-level means you work with ideas such as lists, text and files, not with memory addresses.
  • Interpreted means you run the source file directly with the python command. There is no separate compile step to manage.
  • General-purpose means it is not tied to one job. The same language builds web servers, test frameworks and data reports.

Here is a complete Python program. It stores some test results and prints a summary:

Python
results = {"login": "pass", "search": "pass", "checkout": "fail"} passed = [name for name, status in results.items() if status == "pass"]print("Tests run:", len(results))print("Passed:", ", ".join(passed))
Output
Tests run: 3
Passed: login, search

You do not need to understand every line yet. Notice how little punctuation there is: no semicolons, no curly braces around blocks, no type declarations.

A short history

YearEvent
1991Guido van Rossum publishes the first version of Python
2000Python 2.0 adds list comprehensions and garbage collection of cycles
2008Python 3.0 cleans up the language and is not fully backward compatible
2020Python 2 reaches end of life on 1 January; all new code uses Python 3

The name comes from the comedy group Monty Python, not from the snake.

Key features of Python

FeatureWhat it means for you
Simple, readable syntaxIndentation shows the structure, so code looks the same everywhere
Dynamically typedYou do not declare types; a variable takes the type of its value
Batteries includedThe standard library handles files, JSON, CSV, dates, regex, HTTP and more
Cross-platformThe same script runs on Windows, macOS and Linux
Multi-paradigmWrite procedural, object-oriented or functional code
Huge ecosystemPyPI hosts packages such as pytest, Playwright, requests, NumPy and Pandas
Free and open sourcePython is developed by the Python Software Foundation and the community

Dynamic typing in action: the same name can hold values of different types, and type() tells you what it holds right now.

Python
value = 42print(type(value)) value = "forty-two"print(type(value))
Output
<class 'int'>
<class 'str'>

The Zen of Python

Python’s design ideas are written down as a short poem. Run import this to print it:

Python
import this
Output
The Zen of Python, by Tim Peters

Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!
Note

“Readability counts” and “Simple is better than complex” are the two lines you will feel most while learning. Python code is read far more often than it is written.

What is Python used for?

  • Test automation: pytest, Selenium, Playwright and requests for UI and API testing.
  • Web development: Django, Flask and FastAPI power web sites and REST APIs.
  • Data analysis: NumPy, Pandas and Matplotlib turn raw data into answers.
  • Machine learning and AI: scikit-learn, PyTorch and TensorFlow.
  • Scripting and automation: renaming files, sending reports, cleaning spreadsheets.
  • DevOps and cloud tooling: Ansible, AWS and Azure SDKs, CI scripts.

How Python runs your code

When you run python hello.py:

  1. The interpreter reads your source code and checks the syntax.
  2. It compiles the code to bytecode, a simple instruction format.
  3. The Python virtual machine executes the bytecode line by line.

You can see which interpreter is running and where with the sys module:

Python
import sys, platform print(platform.python_implementation())print(sys.version_info.major, sys.version_info.minor)
Output
CPython
3 15
Tip

The standard interpreter is called CPython because it is written in C. Other implementations exist, such as PyPy (faster for long-running code) and Pyodide, which runs Python in a browser and powers the Try it buttons on this site.

Check your understanding

Quick quiz

1. Who created Python?

2. What does “dynamically typed” mean?

3. Which version should new projects use?

Program Practice

Ready to write code? The basic programs use only variables, arithmetic and print(), so they are a good first set.

Python introduction FAQ

Is Python a compiled or interpreted language?

Both, in a sense. CPython compiles your source to bytecode and then interprets that bytecode. You only ever run one command, python file.py, so it feels interpreted.

Is Python good for beginners?

Yes. Its syntax is short and readable, error messages point to the exact line, and you can get useful results with very little code.

Is Python free?

Yes. Python is open source and free to use for personal and commercial projects.

What is the difference between Python and Java?

Java is statically typed and compiled to JVM bytecode ahead of time; Python is dynamically typed and run directly. Python programs are usually shorter, while Java catches more type errors before the program runs.

Python MCQ Questions and Answers: Free Interview Mock Tests

Prepare for your Python interview with free, timed Python MCQ tests written for QA engineers and developers. Pick a topic and answer 20 random questions in 20 minutes from a 200-question bank. You get your score, every correct answer with an explanation, a score split into QA and developer questions, and an interview readiness score that grows as you practise.

How the Python MCQ tests work

  • 15 interview topics from Python basics to pytest, OOP and pandas. New topics open as their question banks are published.
  • 20 questions per test, 200 per topic: questions you have not seen come first, so about 10 attempts cover a whole topic.
  • 20-minute timer and live progress bar: see how many questions you have answered; the test submits itself when time runs out.
  • Real interview questions: predict-the-output code, common bugs, best practice and test-automation scenarios. Every code question was run on Python 3 to confirm the answer.
  • Instant review: pass mark 70%, the correct answer and a short explanation for every question, and a link to the lesson to revise.
  • Your Python learning progress: topics mastered, topics still to practise and what to study next, saved in your browser.

How interview readiness is calculated

Readiness combines how much you have practised with how well you score: readiness = (tests completed out of 20) × (accuracy). Accuracy is the average of your last three scores in each available topic; a topic you have not tried counts as 0%.

  • 0 to 39%: Getting started
  • 40 to 69%: Developing
  • 70 to 84%: Almost ready
  • 85 to 100%: Interview ready

Python MCQ topics

Learn first, then test yourself

Each test links to the matching lesson in the free Python tutorial. Practise coding with 1,100+ Python practice programs, and if you work in test automation, continue with the Playwright with Python & pytest course and its mock interview.

Frequently asked questions

Are these Python MCQ tests free?

Yes. Every test is free and needs no sign-up. Your results and progress are stored only in your own browser.

Who are these Python MCQs for?

For QA and test automation engineers and for developers preparing for Python interviews. Each question is tagged as a QA or developer question, and your result shows your score in both.

How many questions are in each Python MCQ test?

Each test has 20 multiple-choice questions drawn at random from a 200-question bank for that topic, with a 20-minute time limit and a 70% pass mark.

Are the answers correct?

Every predict-the-output question was executed on Python 3 and its answer is the real output. Each question also has an explanation, so you learn why the answer is right.

Where can I learn the topics before testing?

Every topic links to its lesson in the free sqatools Python tutorial, and the result page shows a “Revise the lesson” button when you do not pass.

Will my progress be saved?

Progress is saved in your browser’s local storage on this device. Clearing site data or switching browsers starts a fresh history.

Python OOP Programs with Solutions

Python Practice › OOP Programs

Python OOP Programs with Solutions

48 programs44 easy4 medium0 hard

48 object-oriented programming exercises: constructors, instance and class variables, class and static methods, every kind of inheritance, overriding, abstract classes, encapsulation, properties and small real-world systems such as bank accounts, carts and courses.

Before you start

Read the Classes & Objects and Inheritance and Polymorphism & Encapsulation lesson first if the topic is new to you.

All programs

Cartesian product of two sets

Python Practice › Set Programs › Program 22

Cartesian product of two sets

EasySet Programs · 22 of 48

Write a Python program to find the cartesian product of two sets.

Input
{1, 2}, {"a", "b"}
Output
[(1, 'a'), (1, 'b'), (2, 'a'), (2, 'b')]

Approach

  1. itertools.product; sort for a stable display.

Solution

Python
from itertools import productprint(sorted(product({1, 2}, {"a", "b"})))
Output
[(1, 'a'), (1, 'b'), (2, 'a'), (2, 'b')]

Learn the concept

New to this topic? Read the lesson, then come back.

More set programs

← All 48 Set Programs

Python Set Programs with Solutions

Python Practice › Set Programs

Python Set Programs with Solutions

48 programs48 easy0 medium0 hard

48 set programs: creating sets, adding and removing items, union, intersection, difference, subsets and frozensets. Sets of strings have no fixed order, so these solutions print sorted(...) whenever the order would otherwise change from run to run.

Before you start

Read the Sets lesson first if the topic is new to you.

All programs

Sort lines by length

Sort lines by length

EasyFile Handling Programs · 15 of 38

Write a Python program to sort the lines of a file by their length.

Output
x
short
medium line
a much longer line here

Approach

  1. sorted(lines, key=len).

Solution

Python
with open("story.txt", "w") as f:    f.write("medium line\nx\na much longer line here\nshort\n") with open("story.txt") as f:    lines = f.read().splitlines()for line in sorted(lines, key=len):    print(line)
Output
x
short
medium line
a much longer line here

Learn the concept

New to this topic? Read the lesson, then come back.

More file handling programs

← All 38 File Handling Programs

Python Projects For Beginners

This article has common Python Projects for beginners, which have all categories of projects from basic to advanced.

Basic Level Projects:

  • Basic Calculator
  • Show Calendar
  • Convert pdf to text
  • Convert image to pdf
  • Convert dictionary to JSON
  • Convert JPEG to PNG
  • Convert JSON to CSV
  • Convert XML to JSON
  • Convert book into audiobook 
  • Decimal to binary convertor and vice versa
  • DNS Records
  • Encrypt and decrypt text
  • Extract zip files
  • Fetch HTTP status code
  • Fetch open ports
  • Hashing passwords
  • Merge csv
  • Merge pdf
  • QR code generator
  • Random password generator

Intermediate Level Projects:

  • Capture screenshot
  • Calculate age
  • Chrome Automation
  • Convert numbers into words
  • Script to encrypt files and folders
  • Article Downloader
  • Duplicate file remover
  • Email GUI
  • Email verification
  • Facebook dp downloader
  • Get wifi password
  • Github repo automation
  • Image to speech
  • Language Translator
  • Password manager
  • Plagiarism checker
  • Python image compressor
  • Send an email with a python
  • Send mail from CSV
  • Set alarm
  • URL shortener

Advance Level Projects:

  • Auto birthday wisher.
  • Auto Backup.
  • Auto-fill the google form.
  • Automate Facebook bot.
  • Automatic certificate generator.
  • Automatic Facebook login
  • Calculator GUI
  • Calendar GUI
  • CLI todo
  • Simple Stopwatch
  • Dictionary GUI
  • Easy cartoonify the image
  • Video Player
  • Extract text from PDF
  • Gesture control media player
  • Google meeting bot
  • Image to sketch
  • Noise reduction script
  • Password manager GUI
  • PDF reader with voice
  • Quote scraper
  • Screen recorder
  • Speech to text
  • Text to speech
  • Text editor
  • Voice Translator
  • Video to audio converter

Split a dictionary into chunks

Split a dictionary into chunks

EasyDictionary Programs · 92 of 94

Write a Python program to split a dictionary into dictionaries of n items.

Input

{"a": 1, "b": 2, "c": 3, "d": 4, "e": 5, "f": 6}, n = 3
Output

[{'a': 1, 'b': 2, 'c': 3}, {'d': 4, 'e': 5, 'f': 6}]

Approach

  1. Slice the list of items in steps of n.

Solution

Python
d = {"a": 1, "b": 2, "c": 3, "d": 4, "e": 5, "f": 6}n = 3items = list(d.items())print([dict(items[i:i + n]) for i in range(0, len(items), n)])

Output
[{'a': 1, 'b': 2, 'c': 3}, {'d': 4, 'e': 5, 'f': 6}]

Learn the concept

New to this topic? Read the lesson, then come back.

More dictionary programs

← All 94 Dictionary Programs

Sort by the sum of list values

Sort by the sum of list values

EasyDictionary Programs · 91 of 94

Write a Python program to map each key to the sum of its list and sort by that sum.

Input
{"x": [1, 5, 6], "y": [4, 8, 2], "c": [3, 9]}
Output
{'x': 12, 'c': 12, 'y': 14}

Approach

  1. Sum the lists, then sort by value.

Solution

Python
d = {"x": [1, 5, 6], "y": [4, 8, 2], "c": [3, 9]}sums = {k: sum(v) for k, v in d.items()}print(dict(sorted(sums.items(), key=lambda kv: kv[1])))
Output
{'x': 12, 'c': 12, 'y': 14}

Learn the concept

New to this topic? Read the lesson, then come back.

More dictionary programs

← All 94 Dictionary Programs