BeginnerLesson 21 of 477 min read6 runnable examples
Lists and tuples both store ordered sequences, and both support indexing, slicing and loops. The difference that matters is that a list can change and a tuple cannot. That one difference decides which to use.
Traceback (most recent call last):
File "main.py", line 1, in <module>
visited = {[0, 0], [0, 1]}
^^^^^^^^^^^^^^^^
TypeError: cannot use 'list' as a set element (unhashable type: 'list')
Use a list when the collection will change: items are added, removed or sorted, such as a shopping cart or a queue of test cases.
Use a tuple when the values belong together and should not change, such as (latitude, longitude), an RGB colour, a function returning several values, or a dictionary key.
Check your understanding
Quick quiz
1. Which can be used as a dictionary key?
Lists are mutable and therefore unhashable.
2. Which uses less memory for the same five numbers?
A list keeps extra capacity so it can grow.
3. You need to store an employee’s (id, name, joining date) record that never changes. Which fits best?
It is a fixed record, so a tuple communicates intent and protects it from accidental changes.
Program Practice
70 Python Tuple Programs
Every program has a step-by-step explanation, colour-coded code and its real output.
Creating and iterating over a tuple is slightly faster and it uses less memory. The difference rarely matters; choose based on whether the data should change.
Why use a tuple instead of a list?
To signal that the data is fixed, to protect it from accidental changes, to use it as a dictionary key or set member, and to save a little memory.
Can a tuple contain a list?
Yes. The tuple cannot be changed, but the list inside it can. Such a tuple is not hashable, so it cannot be a dict key.
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
defgreet():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
defgreet(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.
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
defadd_item(item,basket=[]):# bugbasket.append(item)returnbasketprint(add_item("pen"))print(add_item("book"))# the old pen is still theredefadd_item_fixed(item,basket=None):# fixifbasketisNone:basket=[]basket.append(item)returnbasketprint(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.
and * also work the other way: they spread a list or dict into separate arguments.
Python
defdescribe(name,role,city):returnf"{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
defdiscount(price:float,percent:float=10)->float:"""Return the price after taking off `percent` per cent."""returnround(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:
a and b take the first two values, *rest collects any extra positional values into a tuple, and **opts collects keyword arguments into a dict.
Quick quiz
1. What does a function return if it has no return statement?
Every function returns something; without return it is None.
2. Which definition is valid?
Parameters with defaults must come after those without.
3. Inside def f(*args), what type is args?
*args collects positional arguments into a tuple; **kwargs gives a dict.
4. Why is def f(items=[]) a problem?
The default is created once, so changes persist across calls. Use None instead.
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].
Python
defis_palindrome(text):cleaned="".join(text.lower().split())returncleaned==cleaned[::-1]fortin["Never odd or even","Python"]:print(t,"->",is_palindrome(t))
Output
Never odd or even -> True
Python -> False
split() with no arguments removes all spaces and join glues the words back together. The function returns the comparison result directly, so callers can use it in if statements.
Program Practice
39 Python Function Programs
Every program has a step-by-step explanation, colour-coded code and its real output.
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.
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)
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"inuser)# 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 returndelconfig["timeout"]# removeprint(removed,config)
stock={"pen":40,"notebook":0,"bag":7}foriteminstock:# keysprint(item,end=" ")print()print(list(stock.values()))foritem,qtyinstock.items():# key and value togetherifqty==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={}forwordintext.split():counts[word]=counts.get(word,0)+1print(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.
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.
['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.
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))
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 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.
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:
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.
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.
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.
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.
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:
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.
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.
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.
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.
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:
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:
In this case, the `concatenated_tuples` will be (1, 2, 3, 4, 5, 6), resulting from the concatenation of `tup1` and `tup2`.
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.
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:
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.
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:
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:
In this example, `min(tup)` returns the minimum value of 1, while `max(tup)` returns the maximum value of 6.
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:
In this example, `sorted(tup)` returns a sorted list `[1, 2, 3, 4, 5]` while leaving the original tuple unchanged.
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:
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.
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.
index
0
1
2
3
4
nums
10
20
30
40
50
negative
-5
-4
-3
-2
-1
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
print(nums[0]) # first item
print(nums[-1]) # last item
print(nums[1:4]) # items at index 1, 2, 3
print(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 beforestop. 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
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)
cart.append("bag") # add to the end
cart.insert(1, "ink") # add at index 1
cart[0] = "pencil" # replace an item
print(cart)
last = cart.pop() # remove and return the last item
print(last, cart)
cart.remove("ink") # remove by value
print(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:
dict.fromkeys(emails) builds a dictionary whose keys are the emails. A repeated key is ignored and keeps its first position, so list() of those keys is the unique list in its original order.
Program Practice: Python list programs
Practise what you just learned. Start with the easy programs and work up.
100 Python List Programs
Every program has a step-by-step explanation, colour-coded code and its real output.
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.
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.
index
0
1
2
3
4
5
text
P
Y
T
H
O
N
negative
-6
-5
-4
-3
-2
-1
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 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:].
log="ERROR 2026-11-02 login failed for user asha"print("failed"inlog)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
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"))
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.
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.
prices=[120,45,300,80,45]total=0# accumulateforpinprices:total+=pcount_cheap=0# count matchesforpinprices:ifp<100:count_cheap+=1biggest=prices[0]# track the maximumforpinprices[1:]:ifp>biggest:biggest=pprint(total,count_cheap,biggest)print(sum(prices),sum(1forpinpricesifp<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.
range(1, 10, 2) gives 1, 3, 5, 7, 9. The loop adds 1, 3 and 5, then breaks at 7, so the total is 9.
Quick quiz
1. What numbers does range(3) produce?
range(n) starts at 0 and stops before n.
2. When does a loop’s else block run?
else is skipped if the loop was stopped by break.
3. What does continue do?
continue jumps straight to the next pass.
4. Which loop fits “keep asking until the user types quit”?
You do not know in advance how many times it will run, so use while.
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.
Python
n=40721digit_sum=0reversed_n=0whilen>0:digit=n%10digit_sum+=digitreversed_n=reversed_n*10+digitn//=10print("Sum of digits:",digit_sum)print("Reversed:",reversed_n)
Output
Sum of digits: 14
Reversed: 12704
Each pass peels off the last digit with % 10, adds it to the sum, appends it to reversed_n, then drops it with //= 10. The loop stops when no digits are left.
Program Practice
90 Python Loop Programs
Every program has a step-by-step explanation, colour-coded code and its real output.
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.
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.
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.
name="python"name.upper()# returns a NEW stringprint(name)# the original is unchangedname[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.
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.
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=38iftemperature>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=16ifage>=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.
day="Saturday"is_holiday=Falsehour=22ifdayin("Saturday","Sunday")oris_holiday:print("Weekend rates apply")ifnotis_holidayand9<=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:
Order 650: shipping 0
Order 300: shipping 40
Order 300: shipping 80
The free-shipping rule is tested first because it applies whether or not the order is express. The for line unpacks each tuple into amount and express.
Program Practice
64 Python If-Else Programs
Every program has a step-by-step explanation, colour-coded code and its real output.