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

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.

Python Variables

Python Tutorial › Basics › Variables

Python Variables

BeginnerLesson 8 of 4710 min read10 runnable examples

A variable is a name that refers to a value, so you can use the value later, change it, and make your code readable. In Python you create a variable simply by assigning to it.

In this lesson
  • Create and update variables
  • Follow Python’s naming rules
  • Assign several variables at once
  • Understand that names point to objects

Create a variable

Write a name, an equals sign and a value. Python creates the variable the first time you assign to it. There is no var, let or type declaration.

Python
browser = "chromium"timeout = 30headless = True print(browser, timeout, headless)
Output
chromium 30 True
Note

= means assign, not “is equal to”. timeout = 30 stores 30 under the name timeout. To compare two values you use ==, covered in Operators.

Change a variable

Assigning again replaces the old value. The new value can even be a different type, because Python variables do not have a fixed type; the value does.

Python
count = 1count = count + 1      # read the old value, add 1, store the resultcount += 1             # the same thing, written shorterprint(count) count = "three"        # now it holds a stringprint(count, type(count))
Output
3
three <class 'str'>

Naming rules

RuleValidInvalid
Letters, digits and underscores onlyuser_2user-2, user 2
Cannot start with a digit_2nd, second2nd
Cannot be a keywordclass_nameclass, for
Case-sensitivetotal and Total are different
Python
user-name = "asha"
Output
  File "main.py", line 1
    user-name = "asha"
    ^^^^^^^^^
SyntaxError: cannot assign to expression here. Maybe you meant '==' instead of '='?

Naming conventions

These are not enforced by Python but every Python developer follows them (they come from the PEP 8 style guide):

  • snake_case for variables and functions: max_retries, page_title.
  • UPPER_CASE for constants that should not change: BASE_URL, MAX_RETRIES.
  • PascalCase for classes: LoginPage.
  • Use names that say what the value means: retries beats r, price_in_rupees beats p.

Assign several variables at once

Python
x, y, z = 10, 20, 30           # one value per nameprint(x, y, z) a = b = c = 0                  # the same value to every nameprint(a, b, c) first, *rest = [1, 2, 3, 4]    # * collects the leftovers into a listprint(first, rest)
Output
10 20 30
0 0 0
1 [2, 3, 4]

The number of names on the left must match the number of values, unless one name has *:

Python
x, y = 1, 2, 3
Output
Traceback (most recent call last):
  File "main.py", line 1, in <module>
    x, y = 1, 2, 3
    ^^^^
ValueError: too many values to unpack (expected 2, got 3)

Swap two variables

Many languages need a temporary variable to swap. Python swaps in one line:

Python
a = 10b = 20a, b = b, aprint("a =", a, "b =", b)
Output
a = 20 b = 10

Variables are names for objects

A variable does not contain the value; it refers to an object in memory. Two names can refer to the same object. id() shows an object’s identity and is checks whether two names refer to the same object.

Python
scores = [90, 85]backup = scores           # a second name for the same listbackup.append(70) print(scores)print(backup is scores)
Output
[90, 85, 70]
True

This is why changing a list through one name shows up through the other. Numbers and strings cannot be changed in place, so for them this never surprises you:

Python
a = 5b = ab = b + 1      # creates a new int object; a still refers to 5print(a, b)
Output
5 6
Tip

The Lists lesson shows how to make a real copy with .copy() when you need one.

Delete a variable

del removes a name. Using the name afterwards raises NameError.

Python
temp = 42del tempprint(temp)
Output
Traceback (most recent call last):
  File "main.py", line 3, in <module>
    print(temp)
          ^^^^
NameError: name 'temp' is not defined

Constants

Python has no true constants. By convention a name in UPPER_CASE tells other developers “do not change this”:

Python
BASE_URL = "https://sqatools.in"MAX_RETRIES = 3 for attempt in range(1, MAX_RETRIES + 1):    print(f"Attempt {attempt} of {MAX_RETRIES} on {BASE_URL}")
Output
Attempt 1 of 3 on https://sqatools.in
Attempt 2 of 3 on https://sqatools.in
Attempt 3 of 3 on https://sqatools.in

Check your understanding

Predict the output

a = 3b = aa = a * 2print(a, b)

Quick quiz

1. Which is a valid Python variable name?

2. What does x, y = y, x do?

3. What is the convention for a value that should never change?

4. What does first, *rest = [5, 6, 7] put in rest?

Exercise: shopping cart total

Store the item price, quantity and discount percentage in well-named variables, then print the final amount.

Input
price = 250, quantity = 4, discount = 10%
Expected output
Subtotal: 1000
Final amount: 900.0
Hint 1

The discount amount is subtotal * discount_percent / 100.

Program Practice

Python variables FAQ

Do I need to declare a variable type in Python?

No. Python works out the type from the value you assign. n = 5 is an int and n = "5" is a str. You can add optional type hints, such as n: int = 5, for readability.

How do I swap two variables in Python?

Use tuple unpacking: a, b = b, a. No temporary variable is needed.

What is the difference between = and ==?

= assigns a value to a name. == compares two values and returns True or False.

Can a variable name start with an underscore?

Yes. A single leading underscore, as in _cache, is a convention meaning “internal, do not use from outside”.