A Python list stores multiple values in a single variable. For example, if a class has 40 students, we do not need to create 40 separate variables to store their names. We can store all the names in one list and access each name by using its index.
Lists are ordered, mutable, allow duplicate values, and can store different data types.
| Feature | List | Tuple | Set | Dictionary |
|---|---|---|---|---|
| Mutable | Yes | No | Yes | Yes |
| Access Elements | By indexmy_list[1] |
By indexmy_tuple[1] |
No index | By keymy_dict['key'] |
| Duplicate Values | Allowed | Allowed | Not allowed |
Keys: Not allowed Values: Allowed |
| Ordered | Yes | Yes | No | Yes |
| Example | ['a','c','e'] |
('a','x','y') |
{'a','c','f'} |
{'a':'one','b':'two'} |
my_list=list() # declare an empty list using list constructor
my_list=[] # declare an empty list
my_list=['Alex','Ronald','John']
print(my_list)
Output
['Alex', 'Ronald', 'John']
Run the examples from this lesson directly in your browser. No local Python installation is required.
Open in Google Colab View on GitHub0, the second at position 1, and so on.
my_list=['Alex','Ronald','John']
print(my_list[2])
Output
John
Since indexing starts from 0, my_list[0] gives the first element. Therefore, my_list[2] returns the third element, John.
my_list=['Ronald','John','King','Ravi','Alex']
print(my_list[-1]) # Last element: Alex
print(my_list[-2]) # Second element from the end: Ravi
print(my_list[0:]) # From index 0 to the end
print(my_list[:3]) # From start up to, but not including, index 3
print(my_list[1:4]) # From index 1 up to, but not including, index 4
Output
Alex
Ravi
['Ronald', 'John', 'King', 'Ravi', 'Alex']
['Ronald', 'John', 'King']
['John', 'King', 'Ravi']
print(my_list[1:8]) # Index 8 is beyond the list, but slicing does not raise an error
Output
['John', 'King', 'Ravi', 'Alex']
my_list=['Alex','Ronald','John']
my_list[1]='Ravi'
print(my_list)
Output
['Alex', 'Ravi', 'John']
my_list=['Alex','Ronald','John']
for i in my_list:
print(i)
Output
Alex
Ronald
John
The loop takes each value from my_list one at a time and stores it temporarily in i. The print() function then displays each item.
| Method | Description |
|---|---|
append(x) |
Adds x as one item at the end of the list. |
clear() |
Removes all items from the list. |
copy() |
Returns a shallow copy of the list. |
count(x) |
Returns the number of times x appears in the list. |
extend(iterable) |
Adds each item from an iterable to the end of the list. |
index(x) |
Returns the index of the first occurrence of x. |
insert(i,x) |
Adds x at index i. |
pop([i]) |
Removes and returns the item at index i. Without an index, it removes the last item. |
remove(x) |
Removes the first occurrence of x. |
reverse() |
Reverses the list in place. |
sort() |
Sorts the list in place. |
in 🔝in operator checks whether a value exists in a list. It returns True when the value is present.
my_list=['Alex','Ronald','John']
if 'John' in my_list:
print("Yes, included")
else:
print("No, not included")
Output
Yes, included
in operator to check whether a complete inner list is present.
my_list=[[1,3],[3,4],[4,6]]
if [3,4] in my_list:
print("Yes, present")
else:
print("Not present")
Output
Yes, present
Here, [3,4] matches one complete element of my_list, so the condition becomes True.
5, stopping before 50, with a step of 10.
x=range(5,50,10)
my_list=list(x)
print(my_list)
Output
[5, 15, 25, 35, 45]
split() method, we can break a string into separate parts.
By default, split() uses whitespace as the delimiter and returns the resulting values as a list.
my_string="Welcome to Python"
print(my_string.split())
Output
['Welcome', 'to', 'Python']
squares=[r**2 for r in range(5)]
print(squares)
even_squares=[r**2 for r in range(5) if r%2==0]
print(even_squares)
Output
[0, 1, 4, 9, 16]
[0, 4, 16]
my_list=[5,50,10]
# *my_list unpacks the values as range(5, 50, 10)
for i in range(*my_list):
print(i)
Output is
5
15
25
35
45
Read how list elements are unpacked using * and passed separately to the print() function.
my_list=['Alex', 'Ronald', 'John']
# Unpack list elements and pass them separately to print()
print(*my_list)
Output
Alex Ronald John
The same unpacking operator * can pass list elements as separate arguments to functions such as range() and print().
len() function returns the number of elements present in a list.
my_list=['Alex','Ronald','John']
print("Number of elements:",len(my_list))
Output
Number of elements: 3
The max() function returns the highest value in a list.min() function returns the lowest value in a list.
my_list=[4,2,8,6]
print("Maximum value:", max(my_list))
print("Minimum value:", min(my_list))
Output
Maximum value: 8
Minimum value: 2
sum() of all values by the number of elements returned by len().
mean_value=sum(my_list)/len(my_list)
print("Mean value:",mean_value)
Output
Mean value: 5.0
statistics module. Its mean() function calculates the mean directly.
import statistics
print("Mean value:",statistics.mean(my_list))
Output
Mean value: 5
High School Python ( part of Syllabus)
sum() function to calculate the total of all its elements.
my_list=[1,2,5,6]
my_list_sum=sum(my_list)
print(my_list_sum)
print("Sum by looping")
my_sum=0
for i in my_list:
my_sum=my_sum+i
print(my_sum)
Output
14
Sum by looping
14
The sum() function provides a direct way to add numeric list elements. We can also calculate the same total by using a for loop and adding each value to my_sum.
filter() function to select only the list items that match a condition. In this example, we collect only the strings that contain xy.
def my_check(x):
if x.find('xy') < 0:
return False
else:
return True
list_source=['abcd.php','xyabcd','pqrxy','dataxy']
list_filter=filter(my_check,list_source)
print(list(list_filter))
Output
['xyabcd', 'pqrxy', 'dataxy']
The function my_check() checks each string. The filter() function keeps only the items for which the function returns True.
inin operator makes the condition easier to read.
def my_check(x):
return 'xy' in x
list_source=['abcd.php','xyabcd','pqrxy','dataxy']
list_filter=filter(my_check,list_source)
print(list(list_filter))
Output
['xyabcd', 'pqrxy', 'dataxy']
set stores only unique elements. We can convert a list to a set to remove duplicate values.
my_list=[1,2,3,4,4,5,5,6]
print(set(my_list))
Sample Output
{1, 2, 3, 4, 5, 6}
list() to convert the set back to a list.
my_list=[2,4,1,2,4,5,3]
my_set=set(my_list)
print(my_set)
my_list=list(my_set)
print(my_list)
A set does not guarantee the original list order. Use this method when you need unique values and the original order is not important.
my_list=[1,2,3,4,4,5,5,6]
my_list2=[]
for i in my_list:
if i not in my_list2:
my_list2.append(i)
print(my_list2)
Output
[1, 2, 3, 4, 5, 6]
Here, each value is added to my_list2 only when it is not already present. Read more about the append() method.
Counter class can count how many times each value appears. We can then collect the values that appear more than once.
import collections
my_list=[1,2,3,2,1,5,6,5,5,5]
duplicates=[
item
for item,count in collections.Counter(my_list).items()
if count > 1
]
print(duplicates)
Output
[1, 2, 5]
Read more about finding unique values and counting their occurrences using Counter.
my_list=['a','z','c','z','z','c','b','a']
my_dict={}
for i in my_list:
if i in my_dict:
my_dict[i]=my_dict[i]+1
else:
my_dict[i]=1
print(my_dict)
Output
{'a': 2, 'z': 3, 'c': 2, 'b': 1}
The loop checks each item in my_list. If the item already exists as a key in my_dict, its count increases by 1. Otherwise, the item is added with an initial count of 1.
For larger counting tasks, Python also provides Counter, which can count list elements directly.
High School Python ( part of Syllabus)
&.
list1=[3,2,5,8]
list2=[5,2,8,9]
common_elements=set(list1) & set(list2)
print(common_elements)
Sample Output
{2, 5, 8}
The & operator returns the values that are present in both sets. Here, 2, 5, and 8 are present in both lists.
The result is a set, so the order of the displayed elements is not guaranteed.
-.
list1=[5,10,20,25,15,10,5]
list2=[20,10]
list3=list(set(list1)-set(list2))
print(list3)
The set difference removes 10 and 20 because they are present in list2. It also removes duplicate values.
Since sets do not guarantee the original order, the order of values in list3 may vary.
list1=[5,10,20,25,15,10,5]
list2=[20,10]
list3=[i for i in list1 if i not in list2]
print(list3)
Output
[5, 25, 15, 5]
Here, duplicate values are kept because we check each element of list1 separately.
max() and min() to find the highest and lowest common values.
list1=[3,2,5,8]
list2=[5,2,8,9]
common=set(list1) & set(list2)
print(max(common))
print(min(common))
Output
8
2
The max() and min() functions work here because the two lists contain common elements.
join() method.
If the list contains numbers or other data types, join() cannot use them directly. We can first use map() with str() to convert every element to a string.
my_list=['One',2,'Three']
my_str=",".join(map(str,my_list))
print(my_str)
Output
One,2,Three
Here, map(str,my_list) converts each list element to a string. The join() method then joins the elements by using a comma as the separator.
If all elements in the list are already strings, we can use join() directly without map().
map() to apply a function to each element of a list
random module provides the choice() function to select one random element from a list.
import random
my_list=['Alex','Ron','Ravi','Geek','Rbindra']
random_element=random.choice(my_list)
print(random_element)
Sample Output
Ravi
The output can change each time the program runs because choice() selects one element randomly.
0, the second item is at index 1.
my_list=[
['abc','def','ghi','jkl'],
['mno','pkr','frt','qwr'],
['asd','air','abc','zpq'],
['zae','vbg','qir','zab']
]
second_items=[r[1] for r in my_list]
print(second_items)
Output
['def', 'pkr', 'air', 'vbg']
The list comprehension reads the element at index 1 from each inner list and stores the values in second_items.
in operator to find the row that contains a matching value.
my_list=[
['abc','def','ghi','jkl'],
['mno','pkr','frt','qwr'],
['asd','air','abc','zpq'],
['zae','vbg','qir','zab']
]
for row in my_list:
if 'pkr' in row:
print(row)
Output
['mno', 'pkr', 'frt', 'qwr']
The loop checks each inner list. When 'pkr' is found, Python displays the complete row that contains the matching value.
next()next() with a generator expression.
my_row=next((row for row in my_list if 'pkr' in row), None)
print(my_row)
Output
['mno', 'pkr', 'frt', 'qwr']
The next() function returns the first matching row. If no row contains the search value, it returns None.
import json
path=r"D:\my_data\student.json" # Use the path to your JSON file
with open(path) as fob:
data=json.load(fob)
names=[]
for student in data:
names.append(student['name'])
print(names)
The json.load() function reads the JSON data from the file.
The append() method adds each student's name to the names list.
Using with open() is preferred because Python closes the file automatically after reading it.
names=[student['name'] for student in data]
print(names)
This expression reads the name value from each student record and creates a new list.
sqlite_master. A list comprehension then extracts each table name and stores it in table_names.
from sqlalchemy import create_engine, text
# Connect to the SQLite database
engine=create_engine('sqlite:///your_database.db')
with engine.connect() as my_conn:
# Get table names from the SQLite database
r_set=my_conn.execute(
text("SELECT name FROM sqlite_master WHERE type='table' ORDER BY name")
)
# Create a list containing the table names
table_names=[row[0] for row in r_set]
print(table_names)
For example, if the database contains the tables student, class, and marks, the output can be:
['class', 'marks', 'student']
Each row returned by the query contains a table name. The expression row[0] reads that name, and the list comprehension adds it to table_names.
Try these questions first, then check the Python List practice questions with solutions.
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.