Python Built In Functions

Python Built In Functions

Introduction

Python is a powerful and versatile programming language that comes with a rich set of built-in functions. These functions are pre-defined and readily available, making it easier for developers to accomplish various tasks without having to write the code from scratch. In this tutorial, we will explore what built-in functions are in Python, provide examples of some commonly used built-in functions, and explain the difference between built-in functions and user-defined functions.

What are Built-in Functions in Python?

Built-in functions are functions that are built into the Python programming language. They are always available and do not require any additional installations or imports. These functions are designed to perform common tasks and operations on different types of data. Python provides a wide range of built-in functions, which can be broadly categorized into the following types:

  1. Mathematical Functions: These functions perform various mathematical operations such as calculating absolute values, rounding numbers, finding maximum and minimum values, and more.
  2. String Functions: String functions handle operations on strings, such as concatenation, case conversions, finding substrings, and more.
  3. List Functions: List functions deal with operations on lists, including sorting, adding elements, removing elements, and more.
  4. Dictionary Functions: These functions work with dictionaries, enabling operations like accessing keys, values, merging dictionaries, etc.
  5. File Input/Output Functions: File-related functions help in reading from and writing to files.
  6. Type Conversion Functions: Type conversion functions allow you to convert data from one type to another, such as converting integers to strings or vice versa.
  7. Other Utility Functions: Python also provides several other utility functions for tasks like input/output, formatting, etc.

Now, let’s explore some examples of commonly used built-in functions in Python.

Examples of Python Built-in Functions:

  1. Mathematical Functions:
				
					# Absolute value
abs_result = abs(-10)	
print(abs_result)  # Output: 10

# Rounding
round_result = round(3.14159, 2)
print(round_result)  # Output: 3.14

# Maximum and Minimum
max_result = max(5, 9, 3, 7)
print(max_result)  # Output: 9

min_result = min(5, 9, 3, 7)
print(min_result)  # Output: 3

				
			
  1. String Functions:
				
					# Concatenation
str1 = "Hello"
str2 = "World"
concatenated_str = str1 + " " + str2
print(concatenated_str)  # Output: "Hello World"

# Upper and Lower case
text = "Python is Amazing"
uppercase_text = text.upper()
lowercase_text = text.lower()
print(uppercase_text)  # Output: "PYTHON IS AMAZING"
print(lowercase_text)  # Output: "python is amazing"

# Finding substring
sentence = "Python programming is fun"
substring = "programming"
index = sentence.find(substring)
print(index)  # Output: 7

				
			
  1. List Functions:
				
					# Sorting
numbers = [5, 2, 8, 1, 3]
numbers.sort()
print(numbers)  # Output: [1, 2, 3, 5, 8]

# Appending elements
fruits = ["apple", "banana"]
fruits.append("orange")
print(fruits)  # Output: ['apple', 'banana', 'orange']

# Removing elements
fruits.remove("banana")
print(fruits)  # Output: ['apple', 'orange']

				
			
  1. Dictionary Functions:
				
					# Accessing keys and values
student_scores = {"Alice": 85, "Bob": 92, "Charlie": 78}
keys = student_scores.keys()
values = student_scores.values()
print(keys)  # Output: dict_keys(['Alice', 'Bob', 'Charlie'])
print(values)  # Output: dict_values([85, 92, 78])

# Merging dictionaries
more_scores = {"David": 88, "Eva": 95}
student_scores.update(more_scores)
print(student_scores)
# Output: {'Alice': 85, 'Bob': 92, 'Charlie': 78, 'David': 88, 'Eva': 95}

				
			
  1. File Input/Output Functions:
				
					# Writing to a file
with open("example.txt", "w") as file:
    file.write("Hello, this is an example file.")

# Reading from a file
with open("example.txt", "r") as file:
    content = file.read()
print(content)  # Output: "Hello, this is an example file."

				
			

Difference Between Built-in Functions and User-defined Functions:

The primary difference between built-in functions and user-defined functions lies in their origin and availability. Built-in functions are provided by the Python language itself and are readily available for use without any additional code. On the other hand, user-defined functions are created by the developers themselves to perform specific tasks and are not available in the language by default. Here’s an example to illustrate the difference:

User-defined Function:

				
					def square(x):
    return x ** 2

result = square(5)
print(result)  # Output: 25

				
			

Built-in Function:

				
					num_list = [2, 4, 6, 8, 10]
sum_result = sum(num_list)
print(sum_result)  # Output: 30

				
			

In the user-defined function example, we define a function called “square” that takes a parameter “x” and returns its square. In the built-in function example, we use the “sum” function, which is already provided by Python, to calculate the sum of the elements in the list.

Difference between Built-in functions and anonymous functions (also known as lambda functions)

In Python, the main difference between built-in functions and anonymous functions (also known as lambda functions) lies in their structure, creation, and usage.

Built-in Functions:

Built-in functions in Python are pre-defined functions that are provided by the Python language itself. They are readily available for use without any additional coding or import statements. These functions cover a wide range of tasks and operations, such as mathematical calculations, string manipulations, list operations, file I/O, etc. They are named and can be used repeatedly throughout the code. Here’s an example of using a built-in function to find the length of a list:

				
					# Using the built-in function len() to find the length of a list
numbers = [1, 2, 3, 4, 5]
length = len(numbers)
print(length)  # Output: 5

				
			

In this example, the len() function is a built-in function that returns the number of elements in the list numbers.

Anonymous Functions (Lambda Functions):

Lambda functions are a special type of function in Python that allows you to create small, one-line functions without explicitly defining them using the def keyword. Lambda functions are typically used for simple, one-time tasks and are often used in conjunction with higher-order functions like map(), filter(), and reduce(). Lambda functions have the following structure: lambda arguments: expression

The lambda function takes a set of arguments, performs the specified expression on those arguments, and returns the result of the expression. Here’s an example of a lambda function that calculates the square of a number:

				
					# Using a lambda function to calculate the square of a number
square = lambda x: x**2
result = square(5)
print(result)  # Output: 25

				
			

In this example, we create a lambda function that takes an argument x, calculates the square using the expression x**2, and then we call the lambda function with square(5) to calculate the square of 5.

Key Differences:

  1. Structure and Definition: Built-in functions are predefined and come with Python, whereas lambda functions are created on-the-fly and are not explicitly defined using the def keyword.
  2. Usage and Complexity: Built-in functions are used for a wide range of tasks and can be complex with multiple parameters, whereas lambda functions are typically used for simple operations with one or few parameters.
  3. Naming: Built-in functions have names, and you can call them using their names whenever needed. Lambda functions, on the other hand, do not have names and are often used as temporary, inline functions.
  4. Return Statement: Built-in functions return their results as any other function, using the return statement. Lambda functions automatically return the value of the expression without using the return statement.
  5. Use Cases: Built-in functions are ideal for general-purpose and reusable tasks, while lambda functions are more suited for immediate, short-term, and one-time uses.

Python Functions

Python Tutorial › Functions › Functions

Python Functions

BeginnerLesson 24 of 4714 min read11 runnable examples

A function is a named block of code that you can run whenever you need it. Functions remove repetition, give a name to an idea, and make code easy to test. Every practice program becomes cleaner once it is wrapped in a function.

In this lesson

  • Define and call functions
  • Pass positional, keyword and default arguments
  • Return one or several values
  • Accept any number of arguments with *args and **kwargs

Define and call a function

def starts a function, followed by its name, brackets and a colon. The indented block is the body. Nothing runs until you call the function.

Python
def greet():    print("Hello from a function") greet()greet()

Output
Hello from a function
Hello from a function

Parameters and arguments

Parameters are the names in the definition; arguments are the values you pass in the call.

Python
def greet(name, course):    print(f"Hi {name}, welcome to {course}") greet("Asha", "Python")greet(course="Playwright", name="Ravi")     # keyword arguments: any order

Output
Hi Asha, welcome to Python
Hi Ravi, welcome to Playwright

Return a value

return sends a value back to the caller and ends the function. A function without return gives back None.

Python
def area(width, height):    return width * height def show(x):    print("value:", x) a = area(3, 4)print(a, area(5, 5) + 1)print(show(7))

Output
12 26
value: 7
None

Return several values as a tuple and unpack them:

Python
def stats(numbers):    return min(numbers), max(numbers), sum(numbers) / len(numbers) low, high, avg = stats([4, 8, 15, 16, 23, 42])print(low, high, round(avg, 2))

Output
4 42 18.0
Tip

Prefer functions that return a result over functions that print it. A returned value can be tested, stored or printed later; printed text is gone.

Default arguments

A default value is used when the caller leaves the argument out. Parameters with defaults must come after those without.

Python
def connect(host, port=443, secure=True):    scheme = "https" if secure else "http"    return f"{scheme}://{host}:{port}" print(connect("sqatools.in"))print(connect("localhost", 8080, secure=False))

Output
https://sqatools.in:443
http://localhost:8080
Watch out

Never use a mutable value such as [] as a default. It is created once, when the function is defined, and shared by every call:

Python
def add_item(item, basket=[]):          # bug    basket.append(item)    return basket print(add_item("pen"))print(add_item("book"))                 # the old pen is still there def add_item_fixed(item, basket=None):  # fix    if basket is None:        basket = []    basket.append(item)    return basket print(add_item_fixed("pen"), add_item_fixed("book"))

Output
['pen']
['pen', 'book']
['pen'] ['book']

*args: any number of positional arguments

A parameter with one * collects extra positional arguments into a tuple.

Python
def total(*prices):    print(type(prices).__name__, prices)    return sum(prices) print(total(10, 20, 30))print(total())

Output
tuple (10, 20, 30)
60
tuple ()
0

**kwargs: any number of keyword arguments

Two ** collect extra keyword arguments into a dictionary.

Python
def build_url(base, **params):    query = "&".join(f"{k}={v}" for k, v in params.items())    return f"{base}?{query}" if query else base print(build_url("https://api.example.com/users", page=2, limit=50))print(build_url("https://api.example.com/users"))

Output
https://api.example.com/users?page=2&limit=50
https://api.example.com/users

Unpack arguments in a call

and * also work the other way: they spread a list or dict into separate arguments.

Python
def describe(name, role, city):    return f"{name} ({role}) from {city}" row = ["Meena", "tester", "Pune"]info = {"name": "Ravi", "role": "dev", "city": "Delhi"}print(describe(*row))print(describe(**info))

Output
Meena (tester) from Pune
Ravi (dev) from Delhi

Docstrings and type hints

Python
def discount(price: float, percent: float = 10) -> float:    """Return the price after taking off `percent` per cent."""    return round(price * (1 - percent / 100), 2) print(discount(499.0))print(discount.__doc__)

Output
449.1
Return the price after taking off `percent` per cent.

Type hints (price: float, -> float) document what the function expects. Python does not enforce them, but IDEs and tools such as mypy use them to catch mistakes.

Functions are objects

A function can be stored in a variable, put in a list, or passed to another function:

Python
def shout(text):    return text.upper() + "!" def whisper(text):    return text.lower() + "..." for style in [shout, whisper]:    print(style.__name__, "->", style("Hello")) print(sorted(["banana", "fig", "apple"], key=len))

Output
shout -> HELLO!
whisper -> hello...
['fig', 'apple', 'banana']

Check your understanding

Predict the output

def f(a, b=2, *rest, **opts):    return a, b, rest, opts print(f(1))print(f(1, 5, 6, 7, debug=True))

Quick quiz

1. What does a function return if it has no return statement?

2. Which definition is valid?

3. Inside def f(*args), what type is args?

4. Why is def f(items=[]) a problem?

Exercise: is it a palindrome?

Write is_palindrome(text) that ignores case and spaces, and returns True or False.

Input

"Never odd or even", "Python"
Expected output

Never odd or even -> True
Python -> False
Hint 1

Clean the text first: "".join(text.lower().split()).

Hint 2

Compare the cleaned text with its reverse [::-1].

Program Practice

Python functions FAQ

What is the difference between a parameter and an argument?

A parameter is the name in the function definition (def greet(name)). An argument is the value passed in a call (greet("Asha")).

What are *args and **kwargs in Python?

args collects extra positional arguments into a tuple; kwargs collects extra keyword arguments into a dict. The names are conventions; the and do the work.

Can a Python function return multiple values?

Yes. return a, b returns a tuple, which the caller can unpack: x, y = f().

What is the difference between print and return in a function?

print shows text on the screen. return hands a value back to the caller so it can be used in further code.

Python Dictionaries

Python Tutorial › Data Structures › Dictionaries

Python Dictionaries

BeginnerLesson 23 of 4713 min read10 runnable examples

A dictionary stores data as key-value pairs, so you can look a value up by a meaningful key instead of a position. Dictionaries model JSON, configuration, database rows and counters, which makes them one of the most used types in Python.

In this lesson
  • Create dictionaries and read values safely
  • Add, update and delete keys
  • Loop over keys, values and items
  • Work with nested dicts and merging

Create a dictionary

Write key: value pairs inside curly braces. Keys are usually strings, but any immutable value works.

Python
user = {"name": "Asha", "role": "tester", "years": 4}print(user)print(len(user)) ports = dict(http=80, https=443)       # dict() with keyword argumentsprint(ports)
Output
{'name': 'Asha', 'role': 'tester', 'years': 4}
3
{'http': 80, 'https': 443}

Since Python 3.7, dictionaries keep the order in which keys were inserted.

Read values

Use square brackets with the key. A missing key raises KeyError, so use get() when a key may be absent.

Python
user = {"name": "Asha", "role": "tester"}print(user["name"])print(user.get("email"))                    # None instead of an errorprint(user.get("email", "not provided"))    # with a defaultprint("role" in user)                       # checks keys
Output
Asha
None
not provided
True
Python
user = {"name": "Asha"}print(user["email"])
Output
Traceback (most recent call last):
  File "main.py", line 2, in <module>
    print(user["email"])
          ~~~~^^^^^^^^^
KeyError: 'email'

Add, change and delete

Python
config = {"browser": "chromium", "headless": True} config["timeout"] = 30          # add a new keyconfig["browser"] = "firefox"   # replace an existing valueconfig.update({"retries": 2, "headless": False})print(config) removed = config.pop("retries")  # remove and returndel config["timeout"]           # removeprint(removed, config)
Output
{'browser': 'firefox', 'headless': False, 'timeout': 30, 'retries': 2}
2 {'browser': 'firefox', 'headless': False}

setdefault() returns a key’s value, adding it with a default first if it is missing:

Python
groups = {}for name, team in [("asha", "qa"), ("ravi", "dev"), ("meena", "qa")]:    groups.setdefault(team, []).append(name)print(groups)
Output
{'qa': ['asha', 'meena'], 'dev': ['ravi']}

Loop over a dictionary

Python
stock = {"pen": 40, "notebook": 0, "bag": 7} for item in stock:                  # keys    print(item, end=" ")print() print(list(stock.values())) for item, qty in stock.items():     # key and value together    if qty == 0:        print(item, "is out of stock")
Output
pen notebook bag 
[40, 0, 7]
notebook is out of stock

Count things with a dict

Counting is the classic dictionary job:

Python
text = "the quick brown fox jumps over the lazy dog the end"counts = {}for word in text.split():    counts[word] = counts.get(word, 0) + 1 print(counts["the"])top = max(counts, key=counts.get)print(top, counts[top])
Output
3
the 3
Tip

collections.Counter does this in one line: Counter(text.split()).most_common(1). See the Collections lesson.

Nested dictionaries

Values can be lists or other dictionaries, which is exactly the shape of JSON data.

Python
response = {    "status": 200,    "data": {        "user": {"id": 7, "name": "Ravi"},        "roles": ["admin", "tester"],    },}print(response["data"]["user"]["name"])print(response["data"]["roles"][-1])print(response.get("error", {}).get("message", "no error"))
Output
Ravi
tester
no error

Merge dictionaries

Python
defaults = {"browser": "chromium", "headless": True, "timeout": 30}overrides = {"headless": False} settings = defaults | overrides      # Python 3.9+print(settings)print({**defaults, **overrides} == settings)
Output
{'browser': 'chromium', 'headless': False, 'timeout': 30}
True

When both have the same key, the value from the right-hand dict wins.

Dictionary methods

MethodWhat it does
get(k, default)Value for k, or default if missing
keys(), values(), items()Views of the keys, values or pairs
update(other)Adds or replaces keys from another dict
pop(k)Removes k and returns its value
popitem()Removes and returns the last inserted pair
setdefault(k, d)Returns k‘s value, inserting d first if missing
copy()Shallow copy
clear()Removes everything
dict.fromkeys(keys, v)New dict with each key set to v

Sort a dictionary

Python
scores = {"Asha": 88, "Ravi": 74, "Meena": 93}print(sorted(scores))                                    # keysprint(sorted(scores.items(), key=lambda kv: kv[1], reverse=True))ranked = dict(sorted(scores.items(), key=lambda kv: kv[1], reverse=True))print(ranked)
Output
['Asha', 'Meena', 'Ravi']
[('Meena', 93), ('Asha', 88), ('Ravi', 74)]
{'Meena': 93, 'Asha': 88, 'Ravi': 74}

Check your understanding

Predict the output

d = {"a": 1, "b": 2}d["a"] += 10d.setdefault("c", 3)d.setdefault("a", 99)print(d, d.get("z", 0))

Quick quiz

1. What does d.get("x") return when “x” is not a key?

2. Which loop gives both keys and values?

3. Which of these can NOT be a dictionary key?

4. In a | b, if both dicts have key “x”, whose value is kept?

Exercise: invert a dictionary

Swap keys and values of a country-code dict, then look up the code for “India”.

Input
{"IN": "India", "US": "United States", "JP": "Japan"}
Expected output
{'India': 'IN', 'United States': 'US', 'Japan': 'JP'}
IN
Hint 1

A dict comprehension: {v: k for k, v in codes.items()}.

Program Practice

Python dictionary FAQ

Are Python dictionaries ordered?

Yes. Since Python 3.7, dictionaries preserve insertion order.

How do I check if a key exists in a dictionary?

Use in: if "email" in user:. Use get() when you also want the value.

How do I merge two dictionaries in Python?

Use a | b (Python 3.9+) or {a, b} to create a new dict, or a.update(b) to change a in place.

What is the difference between dict.get() and dict[key]?

dict[key] raises KeyError if the key is missing. dict.get(key) returns None or a default instead.

Python Sets

Python Tutorial › Data Structures › Sets

Python Sets

BeginnerLesson 22 of 4710 min read9 runnable examples

A set is an unordered collection of unique items. Sets remove duplicates automatically, answer “is this item here?” very fast, and support the union and intersection operations you know from maths.

In this lesson
  • Create sets and remove duplicates
  • Add and remove items safely
  • Union, intersection and difference
  • Subset checks and frozenset

Create a set

Write items inside curly braces, or call set() on any iterable. Duplicates are dropped.

Python
tags = {"python", "testing", "python", "api"}print(len(tags))print(sorted(tags)) letters = set("mississippi")print(sorted(letters))
Output
3
['api', 'python', 'testing']
['i', 'm', 'p', 's']
Watch out

{} creates an empty dictionary, not a set. Use set() for an empty set.

Python
print(type({}).__name__, type(set()).__name__)
Output
dict set

Sets are unordered

A set has no positions, so there is no indexing or slicing. Loop over it, or convert it to a sorted list when you need an order.

Python
colors = {"red", "green", "blue"}print(sorted(colors))print(colors[0])
Output
['blue', 'green', 'red']
Traceback (most recent call last):
  File "main.py", line 3, in <module>
    print(colors[0])
          ~~~~~~^^^
TypeError: 'set' object is not subscriptable

Membership is fast

Checking x in some_set takes about the same time however big the set is, while x in some_list has to look through the items one by one. For repeated lookups, convert to a set first.

Python
blocked = {"spam.com", "bad.org", "phish.net"}for domain in ["good.in", "bad.org"]:    print(domain, "blocked" if domain in blocked else "allowed")
Output
good.in allowed
bad.org blocked

Add and remove items

Python
skills = {"python", "sql"}skills.add("selenium")skills.update(["playwright", "python"])   # add severalprint(sorted(skills)) skills.remove("sql")       # KeyError if missingskills.discard("java")     # no error if missingprint(sorted(skills)) item = skills.pop()        # removes an arbitrary itemprint(len(skills))
Output
['playwright', 'python', 'selenium', 'sql']
['playwright', 'python', 'selenium']
2

Set operations

OperationOperatorMethodResult
Uniona | ba.union(b)Items in either set
Intersectiona & ba.intersection(b)Items in both
Differencea - ba.difference(b)Items in a but not b
Symmetric differencea ^ ba.symmetric_difference(b)Items in exactly one
Python
python_devs = {"asha", "ravi", "meena", "john"}java_devs = {"ravi", "john", "sara"} print(sorted(python_devs | java_devs))print(sorted(python_devs & java_devs))print(sorted(python_devs - java_devs))print(sorted(python_devs ^ java_devs))
Output
['asha', 'john', 'meena', 'ravi', 'sara']
['john', 'ravi']
['asha', 'meena']
['asha', 'meena', 'sara']

Subsets and supersets

Python
required = {"python", "sql"}candidate = {"python", "sql", "git"} print(required <= candidate)          # issubsetprint(candidate >= required)          # issupersetprint(required.isdisjoint({"java"}))  # no items in common
Output
True
True
True

Remove duplicates from a list

Python
emails = ["a@x.com", "b@x.com", "a@x.com"]print(len(set(emails)))                   # count of unique itemsprint(sorted(set(emails)))print(list(dict.fromkeys(emails)))        # unique AND original order
Output
2
['a@x.com', 'b@x.com']
['a@x.com', 'b@x.com']

frozenset

A frozenset is an immutable set. Because it cannot change, it can be a dictionary key or an item of another set.

Python
team_a = frozenset({"asha", "ravi"})history = {team_a: "won final"}print(history[frozenset({"ravi", "asha"})])
Output
won final

Check your understanding

Predict the output

a = {1, 2, 3, 4}b = {3, 4, 5}print(sorted(a - b), sorted(b - a), len(a | b), a & b == {3, 4})

Quick quiz

1. What does {} create?

2. Which method does NOT raise an error when the item is missing?

3. What is {1, 2} & {2, 3}?

Exercise: common and unique skills

Two candidates list their skills. Print the skills they share, the skills only the first has, and how many different skills they have together.

Input
c1 = ["python", "sql", "git", "docker"], c2 = ["java", "sql", "git"]
Expected output
Shared: ['git', 'sql']
Only first: ['docker', 'python']
Total different: 5
Hint 1

Convert both lists to sets first.

Program Practice

Python sets FAQ

Is a Python set ordered?

No. Sets do not keep insertion order and cannot be indexed. Use sorted(s) to get an ordered list.

How do I create an empty set in Python?

Use set(). {} creates an empty dictionary.

What is the difference between remove() and discard()?

Both remove an item. remove() raises KeyError if the item is missing; discard() does nothing.

Can a set contain a list?

No. Set items must be hashable. Use a tuple instead of a list.

Python Tuple

Python Tuple Tutorial

Introduction:

Python tuples are a data structure used to store an ordered collection of elements. Unlike lists, tuples are immutable, meaning their values cannot be changed once created. This can be useful in situations where you want to ensure that data is not accidentally modified. Tuples are also hash able, which means they can be used as keys in dictionaries.

Creating a Tuple:

Tuples can be created using parentheses, with elements separated by commas (,) and also bu using tuple() keyword. Here’s an example.

				
					tup = (1,2,3,4)
print(tup) # Output : (1,2,3,4)

tup = tuple(1,2,3,4)
print(tup) # Output : (1,2,3,4)

				
			

Features of python tuple:

A tuple is an immutable sequence in Python that can contain elements of different data types. Here are the key features of a Python tuple:

  • 1). Immutable: Once created, a tuple cannot be modified. You cannot add, remove, or modify elements in a tuple. This immutability ensures data integrity and allows tuples to be used as keys in dictionaries.
  • 2). Ordered : Elements in a tuple are ordered and maintain their positions. The order of elements in a tuple is preserved, and you can access them using their indices.
  • 3). Heterogeneous Data Types : A tuple can store elements of different data types. For example, you can have a tuple containing an integer, a string, and a float.
  • 4). Indexing and Slicing : You can access individual elements of a tuple using their indices. Tuples support both positive and negative indexing, where negative indices count from the end of the tuple. Slicing allows you to extract a portion of the tuple by specifying a range of indices.
  • 5). Iteration : Tuples can be iterated over using loops. This allows you to access each element in the tuple sequentially.
  • 6). Hashability : Tuples are hashable, which means they can be used as keys in dictionaries and elements in sets. This property is due to their immutability.
  • 7). Nesting : Tuples can be nested inside other tuples. This allows you to create complex data structures using tuples.
  • 8). Size Efficiency : Tuples are more memory-efficient compared to lists because they are immutable. This makes tuples a suitable choice when you have a fixed collection of elements that won’t change.
  • 9). Function Arguments and Return Values : Tuples are often used to pack multiple values together and pass them as arguments to functions or return multiple values from a function.
  • 10). Tuple Packing and Unpacking: You can pack multiple values into a tuple using a comma-separated list of values. Similarly, you can unpack a tuple by assigning its elements to individual variables.

Advantages of python tuple:

  1. Immutability:

Tuples in Python are immutable, meaning once created, their elements cannot be modified. This immutability provides several advantages. Firstly, it ensures data integrity by preventing accidental modification of elements. This is particularly useful in scenarios where data should remain constant, such as configuration settings or constant lookup tables. Secondly, immutability allows tuples to be used as keys in dictionaries, as they provide a stable and unchangeable identity. This makes tuples a suitable choice for scenarios where immutability is desired.

  1. Performance Efficiency:

Tuples are more memory-efficient than lists in Python. Since tuples are immutable, they are stored more compactly in memory compared to lists, which can dynamically resize as elements are added or removed. This efficiency can be beneficial when dealing with large collections of data or in scenarios where memory optimization is crucial. Additionally, accessing elements in tuples is generally faster than accessing elements in lists since tuples have a simpler internal structure.

  1. Tuple Packing and Unpacking:

Python tuples support a convenient feature called tuple packing and unpacking. Tuple packing allows you to create tuples by grouping multiple values together. Unpacking, on the other hand, allows you to assign elements of a tuple to individual variables. This feature makes tuples useful in scenarios where you need to return multiple values from a function or swap variable values efficiently. It provides a concise and intuitive way to work with multiple elements simultaneously.

  1. Sequence Operations:

Tuples support sequence operations such as indexing and slicing, similar to lists and strings. This allows you to access specific elements or extract subsets of elements from a tuple efficiently. Additionally, tuples support iteration using loops, making them iterable data structures. This flexibility in sequence operations makes tuples suitable for various use cases, such as iterating over collections, accessing elements by index, or performing operations on specific subsets of data.

  1. Hashability and Uniqueness:

Tuples in Python are hashable, meaning they can be used as keys in dictionaries or elements in sets. This is because tuples are immutable and their hash value remains constant. This property enables efficient lookup and retrieval of data when using tuples as keys or elements. Additionally, tuples can preserve uniqueness, allowing you to store unique combinations of elements in a collection.

Disadvantages of python tuple:

  1. Immutability:

One of the primary disadvantages of tuples is their immutability. Once a tuple is created, its elements cannot be modified. While immutability provides data integrity and stability, it can be restrictive in scenarios where dynamic changes to data are required. If you need to add, remove, or modify elements frequently, a tuple might not be the most suitable data structure. In such cases, mutable data structures like lists might be more appropriate.

  1. Limited Mutability:

While tuples are immutable as a whole, they can contain mutable objects as elements. This means that if a tuple contains mutable objects like lists or dictionaries, those objects can be modified even though the tuple itself cannot be changed. However, care must be taken when modifying mutable objects within a tuple to avoid unexpected behavior or inadvertent modifications.

  1. Lack of Flexibility:

Compared to lists, tuples have limited flexibility. Tuples do not provide built-in methods for adding or removing elements, sorting, or reversing. These operations require converting the tuple to a list, performing the operation, and then converting it back to a tuple. This extra step can be cumbersome and less efficient compared to directly manipulating lists. If you anticipate frequent modifications or dynamic operations on your data, using lists might offer more flexibility.

  1. Inefficient for Large-Scale Modifications:

Due to their immutability, modifying a tuple requires creating a new tuple with the desired modifications. This process can be inefficient and memory-consuming when dealing with large-scale modifications. In such cases, mutable data structures like lists, where elements can be modified in-place, can provide better performance.

  1. Limited Data Analysis Capabilities:

Tuples are not well-suited for complex data analysis tasks or mathematical operations. While they can store numeric values, tuples lack built-in mathematical functions and libraries commonly used for advanced calculations or statistical operations. If your application requires extensive data analysis, other data structures like NumPy arrays or pandas DataFrames might be more suitable.

Deleting python tuple:

In Python, tuples are immutable data structures that allow you to store a collection of elements. Once created, a tuple cannot be modified. However, there may be scenarios where you need to delete a tuple or remove it from memory. In this article, we will explore different techniques to effectively delete a tuple in Python, considering the immutability of tuples.

Tuple Immutability:

Tuples in Python are immutable, meaning their elements cannot be modified or removed individually. This property ensures data integrity and enables tuples to be used as keys in dictionaries. However, it also implies that we cannot directly delete or modify elements within a tuple. Instead, we need to adopt alternative approaches to achieve the desired outcome.

Method 1: Using the “del” keyword:

One way to delete a tuple is by using the `del` keyword. While it cannot delete individual elements within a tuple, it can remove the entire tuple object from memory. Here’s an example:

				
					my_tup = (1, 2, 3, 4)
del my_tup

				
			

In this method, the `del` keyword is used to delete the reference to the tuple.

Method 2: Reassigning the tuple variable:

Another approach to “delete” a tuple is by reassigning the variable that references it. By assigning a new value to the variable, the old tuple becomes unreachable and eligible for garbage collection. Here’s an example:

				
					my_tup = (1, 2, 3, 4)
my_tup = ()

				
			

In this method, an empty tuple is assigned to the variable `my_tup`, effectively replacing the original tuple.

Indexing in python tuple:

In Python, tuples are immutable sequences that allow you to store a collection of elements. Indexing is a fundamental operation that enables you to access individual elements within a tuple.

Understanding Tuple Indexing:

Tuples in Python are ordered collections, meaning the elements maintain a specific order. Each element in a tuple is assigned an index, starting from 0 for the first element. Indexing allows you to retrieve individual elements based on their position within the tuple.

Accessing Elements using Positive Indexing:

Positive indexing is the most common way to access elements in a tuple. It involves using the index value starting from 0 and incrementing by one for each subsequent element.  Here’s an example:

				
					my_tup = (1, 2, 3, 4)
print(my_tuple[0])  # Accessing the first element i.e. 1
print(my_tuple[2])  # Accessing the third element i.e. 3

				
			

In this case, my_tup[0] retrieves the first element 1, and my_tup[2] retrieves the third element 2 from the tuple.

Accessing Elements using Negative Indexing:

Python also supports negative indexing, where the index counts from the end of the tuple. The last element has an index of -1, the second-to-last element has an index of -2, and so on. Negative indexing provides a convenient way to access elements from the end of the tuple. Here’s an example:

				
					my_tup = (1, 2, 3, 4)
print(my_tuple[-1])  # Accessing the last element i.e. 4
print(my_tuple[-2])  # Accessing the second last element i.e. 3

				
			

In this example, `my_tup[-1]` retrieves the last element 4, and `my_tup[-2]` retrieves the second last element 3 from the tuple.

Slicing in Python Tuples:

Understanding Tuple Slicing:

Slicing is a way to extract a portion of a sequence by specifying a range of indices. It is particularly useful when you want to work with a subset of elements within a tuple. The syntax for slicing is `start:stop:step`, where `start` is the starting index, `stop` is the ending index (exclusive), and `step` is the increment value.

Basic Slicing:

To perform a basic slice, you only need to provide the `start` and `stop` indices. This will extract the elements from the starting index up to, but not including, the ending index. Here’s an example:

				
					tup = (1, 2, 3, 4, 5)
print(tup[1:4])  # Extracting elements from index 1 to 3

				
			

In this case, the slice `tup[1:4]` retrieves elements with indices 1, 2, and 3, resulting in the tuple (2, 3, 4).

Step Value in Slicing:

You can also specify a step value to skip elements during the slice. The step value determines the increment between successive elements. Here’s an example:

				
					tup = (1, 2, 3, 4, 5)
print(tup[::3])  # Extracting every third element

				
			

In this example, the slice `tup[::3]` extracts elements with a step size of 3, resulting in the tuple (1, 5).

Negative Indices in Slicing:

Python allows the use of negative indices in slicing. Negative indices count from the end of the tuple. This can be useful when you want to extract elements from the end. Here’s an example:

				
					tup = (1, 2, 3, 4, 5)
print(tup[-4:-1])  # Extracting elements from index -4 to -2

				
			

In this case, the slice `tup [-3:-1]` retrieves elements with indices -4 and -2, resulting in the tuple (2, 3, 4).

Combining Slicing Techniques:

You can combine different slicing techniques to create more complex slices. Here’s an example:

				
					tup = (1, 2, 3, 4, 5)
print(tup[0:5:2])  # Extracting elements from index 0 to 4 with a step size of 2

				
			

In this example, the slice `tup [0:5:2]` extracts elements with indices 0, 2 and 4 resulting in the tuple (1, 3, 5).

Python tuple operators:

  1. Concatenation Operator (+):

The concatenation operator (+) allows you to combine two tuples to create a new tuple. It produces a new tuple that includes all the elements from both tuples, maintaining their order. Here’s an example:

				
					tup1 = (1, 2, 3)
tup2 = (4, 5, 6)
concatenated_tuples = tup1 + tup2

				
			

In this case, the `concatenated_tuples` will be (1, 2, 3, 4, 5, 6), resulting from the concatenation of `tup1` and `tup2`.

  1. Repetition Operator (*):

The repetition operator (*) allows you to create a new tuple by repeating the elements of an existing tuple a specified number of times. It produces a new tuple that contains the repeated elements. Here’s an example:

				
					tup = (1, 2, 3)
repeated_tup = tup * 2

				
			

In this example, the `repeated_tup` will be (1, 2, 3, 4, 1, 2, 3, 4), as the elements of `tup ` are repeated two times.

  1. Comparison Operators (==, !=, <, >, <=, >=):

You can use comparison operators to compare tuples based on their elements. The comparison is performed element-wise, starting from the first element. Here’s an example:

				
					tup1 = (1, 2, 3, 4)
tup2 = (5, 6, 7, 8)
print(tuple1 < tuple2)  # Output: True

				
			

In this case, the `<` operator compares the first element of `tup1` with the first element of `tup2` and returns True because 1 is less than 4.

  1. Membership Operators (in, not in):

Membership operators allow you to check if an element is present in a tuple or not. The `in` operator returns True if the element exists in the tuple, while the `not in` operator returns True if the element does not exist. Here’s an example:

				
					tup = (1, 2, 3)
print(1 in tup)      # Output: True
print(5 not in tup)  # Output: True

				
			

In this example, the first statement returns True as 1 is present in `tup `, while the second statement returns True as 5 is not present.

Python tuple functions:

  1. len():

The `len()` function allows you to determine the length or size of a tuple. It returns the number of elements present in the tuple. Here’s an example:

				
					tup = (1, 2, 3, 4)
tuple_length = len(tup)
print(tuple_length)  # Output: 4

				
			

In this case, `len(tup)` returns 4, as `tup ` contains four elements.

  1. min() and max():

The `min()` and `max()` functions allow you to find the minimum and maximum values, respectively, within a tuple. Here’s an example:

				
					tup = (1, 2, 3, 4, 5, 6)
minimum_value = min(tup)
maximum_value = max(tup)
print(minimum_value)  # Output: 1
print(maximum_value)  # Output: 6

				
			

In this example, `min(tup)` returns the minimum value of 1, while `max(tup)` returns the maximum value of 6.

  1. sum():

The `sum()` function allows you to calculate the sum of all the elements within a tuple. It works for tuples that contain elements that are numeric. Here’s an example:

				
					tup = (1, 2, 3, 4)
total = sum(tup)
print(total)  # Output: 10

				
			

In this case, `sum(tup)` returns 10, which is the sum of all the elements in `tup `.

  1. sorted():

The `sorted()` function returns a new sorted list containing all the elements from a tuple. Here’s an example:

				
					tup = (5, 2, 4, 3, 1)
sorted_list = sorted(tup)
print(sorted_list)  # Output: `[1, 2, 3, 4, 5]

				
			

In this example, `sorted(tup)` returns a sorted list `[1, 2, 3, 4, 5]` while leaving the original tuple unchanged.

  1. count():

The `count()` function allows you to count the occurrences of a specific element within a tuple. It returns the number of times the element appears. Here’s an example:

				
					tup = (1, 1, 2, 3, 2, 4, 1)
element_count = tup.count(1)
print(element_count)  # Output: 3

				
			

In this case, `tup.count(1)` returns 3, as the value 1 appears three times within `tup `.

Python Lists

Python Tutorial › Data Structures › Lists

Python Lists

BeginnerLesson 18 of 4712 min read11 runnable examples

A list stores many values in one variable, in order. You will use lists in almost every Python program you write, from a shopping cart to a set of test results.

In this lesson

  • Create lists of any type
  • Read items with indexing and slicing
  • Add, change and remove items
  • Loop through a list
  • Sort a list two ways
  • Avoid the shared-list copy bug

What is a list in Python?

A list is written with square brackets, with items separated by commas. One list can hold numbers, strings, booleans, None and even other lists.

Python
fruits = ["apple", "banana", "cherry"]mixed = [1, "two", 3.0, True, None]empty = [] print(fruits)print(type(fruits))print(len(mixed), len(empty))

Output
['apple', 'banana', 'cherry']
<class 'list'>
5 0
Note

Lists are ordered (items keep their position), mutable (you can change them after creating them) and they allow duplicates.

You can also build a list from any iterable with list(), for example from a string or a range.

Python
print(list("abc"))print(list(range(1, 6)))

Output
['a', 'b', 'c']
[1, 2, 3, 4, 5]

Indexing and slicing

Every item has a position, called its index. Counting starts at 0 from the left and at -1 from the right.

Python
nums = [10, 20, 30, 40, 50] print(nums[0])      # first itemprint(nums[-1])     # last itemprint(nums[1:4])    # items at index 1, 2, 3print(nums[::-1])   # reversed copy

Output
10
50
[20, 30, 40]
[50, 40, 30, 20, 10]
Tip

A slice nums[start:stop] includes start but stops before stop. That is why nums[1:4] returns three items. Leave out start or stop to go from the beginning or to the end.

Reading an index that does not exist raises an IndexError. A slice never does: it just returns fewer items.

Python
nums = [10, 20, 30]print(nums[1:10])print(nums[5])

Output
[20, 30]
Traceback (most recent call last):
  File "main.py", line 3, in <module>
    print(nums[5])
          ~~~~^^^
IndexError: list index out of range

Add, change and remove items

For every built-in method with examples, see the full guide to Python list methods and functions.

Python
cart = ["pen", "book"] cart.append("bag")        # add to the endcart.insert(1, "ink")     # add at index 1cart[0] = "pencil"        # replace an itemprint(cart) last = cart.pop()         # remove and return the last itemprint(last, cart) cart.remove("ink")        # remove by valueprint(cart)

Output
['pencil', 'ink', 'book', 'bag']
bag ['pencil', 'ink', 'book']
['pencil', 'book']

Python list methods you will use most

Method What it does Returns
append(x) Adds x to the end None
insert(i, x) Adds x before index i None
extend(items) Adds every item from another iterable None
remove(x) Removes the first x; raises ValueError if it is missing None
pop(i=-1) Removes the item at index i the removed item
index(x) Finds the position of the first x int
count(x) Counts how often x appears int
sort() / reverse() Reorders the list in place None
clear() Removes every item None
copy() Makes a shallow copy a new list

append() adds its argument as one item, while extend() adds each item separately:

Python
a = [1, 2]a.append([3, 4])print(a) b = [1, 2]b.extend([3, 4])print(b)

Output
[1, 2, [3, 4]]
[1, 2, 3, 4]

Loop through a list

A for loop visits each item in order. enumerate() gives you the position and the item together, so you do not need a counter variable.

Python
tasks = ["write tests", "run tests", "fix bugs"] for number, task in enumerate(tasks, start=1):    print(f"{number}. {task}")

Output
1. write tests
2. run tests
3. fix bugs

Use in to check whether a value is in a list:

Python
browsers = ["chromium", "firefox", "webkit"]print("firefox" in browsers)print("edge" in browsers)

Output
True
False

Sort a list

Python
scores = [72, 95, 58, 88] print(sorted(scores))          # new sorted listprint(scores)                  # original is unchanged scores.sort(reverse=True)      # sorts in placeprint(scores)

Output
[58, 72, 88, 95]
[72, 95, 58, 88]
[95, 88, 72, 58]
Watch out

scores.sort() changes the list and returns None. Writing scores = scores.sort() throws your list away. Use sorted(scores) when you need a new list.

Pass key= to sort by something other than the value itself, such as the length of each word:

Python
words = ["banana", "fig", "apple"]print(sorted(words, key=len))

Output
['fig', 'apple', 'banana']

Copy a list without surprises

Assigning a list to a new name does not copy it. Both names point at the same list, so a change through one name shows up in the other.

Python
a = [1, 2]b = a            # b is the SAME list, not a copyb.append(3)print(a) c = a.copy()     # c is a new listc.append(4)print(a, c)

Output
[1, 2, 3]
[1, 2, 3] [1, 2, 3, 4]

Check your understanding

Predict the output

x = [1, 2, 3]y = x * 2print(y, len(y))

Quick quiz

1. What does [10, 20, 30][-1] return?

2. Which call removes and returns the last item?

3. After b = a and b.append(3), what is in a?

4. What does [3, 1, 2].sort() evaluate to?

Exercise: remove duplicate emails

You have a list of signup emails with repeats. Build a list that keeps each email once, in the order it first appeared.

Input

["a@x.com", "b@x.com", "a@x.com", "c@x.com", "b@x.com"]
Expected output

['a@x.com', 'b@x.com', 'c@x.com']
Hint 1

A set removes duplicates but does not keep the order.

Hint 2

Dictionary keys are unique and keep insertion order.

Program Practice: Python list programs

Practise what you just learned. Start with the easy programs and work up.

Python lists FAQ

What is the difference between a list and a tuple in Python?

A list is mutable, so you can add, change and remove items. A tuple is immutable: once created, its items cannot change. Use a tuple for fixed data such as coordinates. See List vs Tuple.

How do I check if an item is in a list?

Use the in operator: "apple" in fruits returns True or False.

What is the difference between append() and extend()?

append(x) adds x as one item, even if x is a list. extend(items) adds each item of items separately.

How do I remove duplicates from a list and keep the order?

Use list(dict.fromkeys(items)). list(set(items)) also removes duplicates but does not keep the original order.

Can a Python list hold different data types?

Yes. A list can mix integers, strings, floats, booleans, None and other lists, although lists of one type are easier to work with.

Python Strings & Methods

Python Tutorial › Strings › Strings & Methods

Python Strings & Methods

BeginnerLesson 16 of 4714 min read11 runnable examples

A string is a piece of text: a name, a URL, a log line, a whole file. Python strings come with dozens of built-in methods, and knowing the common ones will save you from writing loops for everyday text work.

In this lesson
  • Create strings with any quote style
  • Index and slice text
  • Use the most common string methods
  • Split text into parts and join it back

Create a string

Use single or double quotes; they mean the same thing. Pick the one that avoids escaping quotes inside the text. Triple quotes allow several lines.

Python
a = 'single quotes'b = "double quotes, with an 'apostrophe' inside"c = """Line oneLine two"""print(a)print(b)print(c)print(len(c))
Output
single quotes
double quotes, with an 'apostrophe' inside
Line one
Line two
17

A raw string, written r"...", ignores backslash escapes. It is handy for Windows paths and regular expressions:

Python
print("C:\new\table")      # \n and \t become a newline and a tabprint(r"C:\new\table")     # printed exactly as written
Output
C:
ew	able
C:\new\table

Index and slice

Strings are sequences of characters, so they support the same indexing and slicing as lists.

Python
text = "PYTHON"print(text[0], text[-1])print(text[0:2], text[2:], text[:-2])print(text[::2])       # every second characterprint(text[::-1])      # reversed
Output
P N
PY THON PYTH
PTO
NOHTYP

Strings are immutable

You cannot change a character in place. Methods return a new string and leave the original alone.

Python
word = "python"upper_word = word.upper()print(word, upper_word)word[0] = "P"
Output
python PYTHON
Traceback (most recent call last):
  File "main.py", line 4, in <module>
    word[0] = "P"
    ~~~~^^^
TypeError: 'str' object does not support item assignment

To “change” a string, build a new one and assign it: word = "P" + word[1:].

Change case

Python
title = "pYthon tUTORIAL"print(title.upper())print(title.lower())print(title.title())print(title.capitalize())print(title.swapcase())
Output
PYTHON TUTORIAL
python tutorial
Python Tutorial
Python tutorial
PyTHON Tutorial
Python
log = "ERROR 2026-11-02 login failed for user asha"print("failed" in log)print(log.startswith("ERROR"), log.endswith(".py"))print(log.find("login"))        # index of the first matchprint(log.find("logout"))       # -1 when not foundprint(log.count("a"))
Output
True
True False
17
-1
3
Tip

find() returns -1 when the text is missing, while index() raises ValueError. Use in when you only need yes or no.

Clean up text

Python
raw = "   Pune, Maharashtra \n"print(repr(raw.strip()))print(repr(raw.lstrip()), repr(raw.rstrip()))print("--report--".strip("-"))print("2026-11-02".replace("-", "/"))print("aaa".replace("a", "b", 2))     # only the first 2
Output
'Pune, Maharashtra'
'Pune, Maharashtra \n' '   Pune, Maharashtra'
report
2026/11/02
bba

Split and join

split() breaks a string into a list. join() does the opposite: it glues a list of strings together with the string you call it on.

Python
csv_line = "asha,tester,pune"fields = csv_line.split(",")print(fields) sentence = "  learn   python   step by step "words = sentence.split()        # no argument: split on any run of whitespaceprint(words) print(" ".join(words))print("-".join(["2026", "11", "02"]))print(list("abc"))
Output
['asha', 'tester', 'pune']
['learn', 'python', 'step', 'by', 'step']
learn python step by step
2026-11-02
['a', 'b', 'c']

Check what a string contains

Python
for s in ["2026", "python", "Py3", "  ", "3.5"]:    print(repr(s).ljust(9), s.isdigit(), s.isalpha(), s.isalnum(), s.isspace())
Output
'2026'    True False True False
'python'  False True True False
'Py3'     False False True False
'  '      False False False True
'3.5'     False False False False

The columns are isdigit(), isalpha(), isalnum() and isspace(). Note that "3.5".isdigit() is False because . is not a digit.

Alignment and padding

Python
for name, score in [("Asha", 91), ("Ravi", 7), ("Meenakshi", 100)]:    print(name.ljust(10), str(score).rjust(4), str(score).zfill(5))print("menu".center(20, "*"))
Output
Asha         91 00091
Ravi          7 00007
Meenakshi   100 00100
********menu********

Common string methods

MethodReturns
upper(), lower(), title()Text in a different case
strip(), lstrip(), rstrip()Text without surrounding whitespace (or given characters)
replace(old, new)Text with every old replaced
split(sep)A list of parts
sep.join(items)One string from a list of strings
find(sub) / index(sub)Position of sub (-1 / error if missing)
count(sub)How often sub appears
startswith(x) / endswith(x)True or False
isdigit(), isalpha(), isalnum()True or False
ljust(), rjust(), center(), zfill()Padded text

Loop over a string

Python
word = "level"vowels = 0for ch in word:    if ch in "aeiou":        vowels += 1print("vowels:", vowels)print("palindrome:", word == word[::-1])
Output
vowels: 2
palindrome: True

Check your understanding

Predict the output

s = "Hello, World"print(s[7:], s.lower().count("l"), s.split(", "))

Quick quiz

1. What does "python"[1:4] return?

2. What does "a-b-c".split("-") return?

3. Why does name[0] = "J" fail?

4. Which returns -1 when the text is not found?

Exercise: initials and username

From a full name, print the initials in upper case and a username made of the lower-case first name and the length of the full name.

Input
"  meena  ravi  kumar "
Expected output
MRK
meena16
Hint 1

split() without arguments handles the extra spaces.

Hint 2

"".join(...) can build the initials from a list.

Program Practice

Python strings FAQ

How do I reverse a string in Python?

Use slicing with a step of -1: text[::-1]. "".join(reversed(text)) also works.

How do I check if a string contains a substring?

Use in: "py" in "python" is True. Use find() when you also need the position.

Are Python strings mutable?

No. Every method returns a new string. To change a variable, assign the new string to it: name = name.strip().

What is the difference between split() and split(” “)?

split() splits on any run of whitespace and ignores leading and trailing spaces. split(" ") splits on every single space, so repeated spaces give empty strings.

Python Loops: for & while

Python Tutorial › Control Flow › Loops: for & while

Python Loops: for & while

BeginnerLesson 15 of 4714 min read12 runnable examples

A loop repeats a block of code. Use a for loop to go through every item in a collection, and a while loop to repeat until a condition changes. Loops are behind almost every practice program on this site.

In this lesson
  • Loop over lists, strings and dicts with for
  • Count with range()
  • Repeat until a condition with while
  • Control loops with break, continue and else

The for loop

A for loop takes each item from a collection in turn and runs the block once per item.

Python
browsers = ["chromium", "firefox", "webkit"] for browser in browsers:    print("Testing on", browser)print("All browsers done")
Output
Testing on chromium
Testing on firefox
Testing on webkit
All browsers done

It works with anything you can iterate over, including strings, tuples, sets, dicts and files:

Python
for ch in "SQA":    print(ch)
Output
S
Q
A

Count with range()

range() produces a sequence of numbers on demand. It stops before the end value.

CallNumbers
range(5)0, 1, 2, 3, 4
range(2, 6)2, 3, 4, 5
range(0, 10, 3)0, 3, 6, 9
range(5, 0, -1)5, 4, 3, 2, 1
Python
for i in range(1, 6):    print(i, "squared is", i * i) print(list(range(10, 0, -2)))
Output
1 squared is 1
2 squared is 4
3 squared is 9
4 squared is 16
5 squared is 25
[10, 8, 6, 4, 2]

Index and value: enumerate()

Python
steps = ["open page", "log in", "add to cart"] for number, step in enumerate(steps, start=1):    print(f"Step {number}: {step}")
Output
Step 1: open page
Step 2: log in
Step 3: add to cart

Two lists side by side: zip()

Python
names = ["Asha", "Ravi", "Meena"]scores = [91, 78, 85] for name, score in zip(names, scores):    print(f"{name:6} {score}")
Output
Asha   91
Ravi   78
Meena  85

Loop over a dictionary

Python
stock = {"pen": 40, "notebook": 0, "bag": 7} for item, qty in stock.items():    status = "out of stock" if qty == 0 else f"{qty} left"    print(item, "-", status)
Output
pen - 40 left
notebook - out of stock
bag - 7 left

The while loop

while repeats as long as its condition is true. Make sure something in the loop changes the condition, or it never stops.

Python
balance = 1000year = 0 while balance < 2000:    balance *= 1.08          # 8% growth per year    year += 1 print(f"Doubled after {year} years: {balance:.2f}")
Output
Doubled after 10 years: 2158.92
Watch out

while True: loops forever unless a break stops it. If a program seems stuck, press Ctrl+C in the terminal to stop it.

break and continue

  • break leaves the loop immediately.
  • continue skips the rest of this pass and goes to the next item.
Python
numbers = [4, 7, -1, 12, 0, 9] for n in numbers:    if n < 0:        print("skip negative", n)        continue    if n == 0:        print("zero found, stopping")        break    print("processing", n)
Output
processing 4
processing 7
skip negative -1
processing 12
zero found, stopping

else on a loop

A loop’s else block runs only if the loop finished without break. It is perfect for “search, and report if not found”:

Python
users = ["asha", "ravi", "meena"]wanted = "john" for user in users:    if user == wanted:        print("Found", wanted)        breakelse:    print(wanted, "not found")
Output
john not found

Nested loops

A loop inside a loop runs the inner loop completely for every pass of the outer one.

Python
for row in range(1, 4):    for col in range(1, 4):        print(row * col, end="\t")    print()
Output
1	2	3	
2	4	6	
3	6	9	

Patterns are a classic exercise for nested loops:

Python
rows = 4for i in range(1, rows + 1):    print(" " * (rows - i) + "*" * (2 * i - 1))
Output
   *
  ***
 *****
*******

Common loop patterns

Python
prices = [120, 45, 300, 80, 45] total = 0                       # accumulatefor p in prices:    total += p count_cheap = 0                 # count matchesfor p in prices:    if p < 100:        count_cheap += 1 biggest = prices[0]             # track the maximumfor p in prices[1:]:    if p > biggest:        biggest = p print(total, count_cheap, biggest)print(sum(prices), sum(1 for p in prices if p < 100), max(prices))   # built-in shortcuts
Output
590 3 300
590 3 300
Tip

Write the loop yourself while learning, because interviewers and practice programs ask for it. In real code, prefer sum(), max(), min() and any() when they fit.

Check your understanding

Predict the output

total = 0for i in range(1, 10, 2):    if i == 7:        break    total += iprint(total)

Quick quiz

1. What numbers does range(3) produce?

2. When does a loop’s else block run?

3. What does continue do?

4. Which loop fits “keep asking until the user types quit”?

Exercise: digits of a number

Use a while loop to print the sum of the digits of a number and the number reversed.

Input
40721
Expected output
Sum of digits: 14
Reversed: 12704
Hint 1

n % 10 gives the last digit and n // 10 removes it.

Program Practice

Python loops FAQ

What is the difference between a for loop and a while loop?

A for loop goes through the items of a collection or a range, so the number of passes is known. A while loop repeats until its condition becomes false.

How do I loop with an index in Python?

Use enumerate(): for i, item in enumerate(items):. Avoid for i in range(len(items)) unless you really need the number alone.

How do I loop backwards in Python?

Use reversed(items) or range(start, stop, -1), for example for i in range(10, 0, -1):.

Does Python have a do-while loop?

No. Write while True: and break at the end of the body when the condition is met.

Python Data Types

Python Tutorial › Basics › Data Types

Python Data Types

BeginnerLesson 9 of 4711 min read8 runnable examples

Every value in Python has a type, and the type decides what you can do with it: you can add two numbers, make a string upper case, or append to a list. This lesson is a tour of the built-in types you will use every day.

In this lesson
  • The built-in data types at a glance
  • Check a value’s type with type() and isinstance()
  • Mutable vs immutable types
  • Choose the right collection for the job

Built-in data types at a glance

CategoryTypeExampleNotes
Textstr"hello"Immutable sequence of characters
Numbersint42, -7Whole numbers of any size
float3.14, 1e-3Decimal numbers
complex2 + 3jUsed in maths and engineering
BooleanboolTrue, FalseResult of comparisons
NothingNoneTypeNone“No value yet”
Sequenceslist[1, 2, 3]Ordered, changeable
tuple(1, 2, 3)Ordered, unchangeable
rangerange(5)Sequence of numbers, created on demand
Mappingdict{"id": 7}Key-value pairs
Setsset{1, 2, 3}Unique items, no order
Binarybytesb"abc"Raw bytes from files and networks

Check the type of a value

type() returns the exact type of a value:

Python
values = [42, 3.14, 2 + 3j, "py", True, None, [1], (1,), {1}, {"a": 1}, range(3), b"x"]for v in values:    print(repr(v).ljust(10), type(v).__name__)
Output
42         int
3.14       float
(2+3j)     complex
'py'       str
True       bool
None       NoneType
[1]        list
(1,)       tuple
{1}        set
{'a': 1}   dict
range(0, 3) range
b'x'       bytes

Use isinstance() in real code. It also accepts a tuple of types and understands subclasses:

Python
price = 99.5print(isinstance(price, float))print(isinstance(price, (int, float)))print(isinstance(True, int))     # bool is a subclass of int
Output
True
True
True

Numbers

Python
big = 2 ** 100          # ints never overflowprint(big)print(7 / 2, 7 // 2)    # / always gives a float, // rounds downprint(0.1 + 0.2)        # floats are approximate
Output
1267650600228229401496703205376
3.5 3
0.30000000000000004
Note

0.1 + 0.2 is not exactly 0.3 because floats are stored in binary. Use round() for display, or the decimal module for money. The Numbers & Math lesson goes deeper.

Strings

A string is text in single, double or triple quotes. Strings support indexing, slicing and many methods.

Python
course = "Python Tutorial"print(course.upper())print(course[0], course[-1])print(len(course))print("Tut" in course)
Output
PYTHON TUTORIAL
P l
15
True

Booleans and None

True and False come from comparisons and are used by if and while. None means “no value”.

Python
is_logged_in = 5 > 3print(is_logged_in, type(is_logged_in)) result = Noneprint(result is None)
Output
True <class 'bool'>
True

Every value is either “truthy” or “falsy”. Empty values and zero are falsy:

Python
for v in [0, 1, "", "a", [], [0], None]:    print(repr(v).ljust(5), bool(v))
Output
0     False
1     True
''    False
'a'   True
[]    False
[0]   True
None  False

Collections: list, tuple, set, dict

Python
skills = ["python", "sql", "python"]          # list: ordered, duplicates allowedpoint = (12.5, 77.3)                          # tuple: fixed recordunique_skills = set(skills)                   # set: duplicates removeduser = {"name": "Asha", "role": "tester"}     # dict: look up by key print(skills)print(point[0])print(len(unique_skills))print(user["role"])
Output
['python', 'sql', 'python']
12.5
2
tester
NeedUse
An ordered list of items you will changelist
A fixed group of values, such as coordinatestuple
Unique items, or fast “is it in here?” checksset
Look up a value by a keydict

Mutable vs immutable

A mutable object can change after it is created; an immutable one cannot.

  • Immutable: int, float, bool, str, tuple, frozenset, bytes.
  • Mutable: list, dict, set, bytearray.
Python
name = "python"name.upper()           # returns a NEW stringprint(name)            # the original is unchanged name[0] = "P"          # strings cannot be changed in place
Output
python
Traceback (most recent call last):
  File "main.py", line 5, in <module>
    name[0] = "P"          # strings cannot be changed in place
    ~~~~^^^
TypeError: 'str' object does not support item assignment
Watch out

Because lists and dicts are mutable, passing one to a function lets that function change your data. Strings and numbers are safe from that.

Check your understanding

Predict the output

print(type(7 / 7).__name__, type(7 // 7).__name__, type("7").__name__)

Quick quiz

1. What is the type of (5,)?

2. Which type removes duplicates automatically?

3. Which of these is immutable?

4. What does bool([]) return?

Exercise: describe each value

Loop over the list and print each value with its type name and whether it is truthy.

Input
[0, 2.5, "", "hi", None, [3]]
Expected output
0      int       False
2.5    float     True
''     str       False
'hi'   str       True
None   NoneType  False
[3]    list      True
Hint 1

type(v).__name__ gives the type name as a string.

Program Practice

Python data types FAQ

How many data types are there in Python?

Python has about a dozen commonly used built-in types: int, float, complex, bool, str, list, tuple, range, dict, set, frozenset, bytes and NoneType. You can also create your own with classes.

How do I check the data type of a variable?

Use type(x) to see the type, or isinstance(x, int) to test it.

What is the difference between mutable and immutable types?

Mutable objects such as lists and dicts can be changed in place. Immutable objects such as strings, numbers and tuples cannot; operations on them return new objects.

Is a string a sequence in Python?

Yes. A string is an immutable sequence of characters, so it supports indexing, slicing, len() and in.

Python If…Else

Python Tutorial › Control Flow › If…Else

Python If…Else

BeginnerLesson 13 of 4711 min read10 runnable examples

Programs need to make decisions: grant access or not, pass or fail, discount or full price. Python makes these decisions with if, elif and else.

In this lesson
  • Run code only when a condition is true
  • Choose between branches with elif and else
  • Nest conditions and combine them
  • Write one-line conditional expressions

The if statement

if runs its indented block only when the condition is true.

Python
temperature = 38 if temperature > 37.5:    print("Fever detected")    print("Please see a doctor")print("Check complete")
Output
Fever detected
Please see a doctor
Check complete

The condition can be any expression. Python treats it as true or false using the truthiness rules from Operators & Booleans.

if … else

else runs when the condition is false. Exactly one of the two blocks runs.

Python
age = 16 if age >= 18:    print("You can vote")else:    print(f"You can vote in {18 - age} years")
Output
You can vote in 2 years

if … elif … else

elif (short for “else if”) checks another condition. Python tests the conditions from top to bottom and runs only the first block whose condition is true.

Python
marks = 74 if marks >= 90:    grade = "A"elif marks >= 75:    grade = "B"elif marks >= 60:    grade = "C"else:    grade = "F" print("Grade:", grade)
Output
Grade: C
Watch out

Order matters. If you test marks >= 60 first, a score of 95 would get “C”, because the first true branch wins and the rest are skipped.

Nested if

An if can sit inside another if. Each level adds 4 spaces of indentation.

Python
username = "admin"password = "s3cret" if username == "admin":    if password == "s3cret":        print("Welcome, admin")    else:        print("Wrong password")else:    print("Unknown user")
Output
Welcome, admin

Deep nesting is hard to read. Often you can flatten it with and:

Python
username, password = "admin", "s3cret" if username == "admin" and password == "s3cret":    print("Welcome, admin")else:    print("Login failed")
Output
Welcome, admin

Combine conditions

Python
day = "Saturday"is_holiday = Falsehour = 22 if day in ("Saturday", "Sunday") or is_holiday:    print("Weekend rates apply") if not is_holiday and 9 <= hour <= 18:    print("Office is open")else:    print("Office is closed")
Output
Weekend rates apply
Office is closed

Conditional expression (one-line if)

For a simple choice between two values, write the condition inline:

Python
stock = 0status = "In stock" if stock > 0 else "Sold out"print(status) n = 7print("even" if n % 2 == 0 else "odd")
Output
Sold out
odd

Empty blocks with pass

A block cannot be empty. Use pass as a placeholder while you are still writing the code:

Python
feature_ready = False if feature_ready:    pass          # TODO: call the new featureelse:    print("Using the old feature")
Output
Using the old feature

Common mistakes

Using = instead of == in a condition is a syntax error:

Python
x = 5if x = 5:    print("five")
Output
  File "main.py", line 2
    if x = 5:
       ^^^^^
SyntaxError: invalid syntax. Maybe you meant '==' or ':=' instead of '='?

x == 1 or 2 does not check whether x is 1 or 2. It means (x == 1) or 2, and 2 is always truthy:

Python
x = 7print(bool(x == 1 or 2))       # always True: a bugprint(x == 1 or x == 2)        # correctprint(x in (1, 2))             # correct and shorter
Output
True
False
False

Check your understanding

Predict the output

n = 15if n % 3 == 0:    print("Fizz")elif n % 5 == 0:    print("Buzz")else:    print(n)

Quick quiz

1. How many branches of an if/elif/else chain run?

2. What does "yes" if 0 else "no" evaluate to?

3. Which correctly tests whether x is 1 or 2?

Exercise: shipping cost

Orders of 500 or more ship free. Otherwise shipping is 40, or 80 for express. Print the shipping cost for each order.

Input
(650, False), (300, False), (300, True)
Expected output
Order 650: shipping 0
Order 300: shipping 40
Order 300: shipping 80
Hint 1

Check the free-shipping rule first.

Program Practice

Python if else FAQ

What is elif in Python?

elif means “else if”. It adds another condition to an if statement and is checked only when all the conditions above it were false.

Does Python have a switch statement?

Python 3.10 added match / case, which covers switch-style logic and much more. See Match Case.

How do I write an if else in one line in Python?

Use a conditional expression: result = "pass" if score >= 50 else "fail".

Can I have an if without an else?

Yes. else is optional. Without it, nothing happens when the condition is false.