Python List: Create, Access, Slice and Modify Items


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 index
my_list[1]
By index
my_tuple[1]
No index By key
my_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'}

Declaring a List 🔝

Declaring an empty list
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']

Python Lists for Beginners - Create, Access, Slice, len(), max(), min() and Mean

Practice Python Lists Part 1 in Google Colab

Run the examples from this lesson directly in your browser. No local Python installation is required.

Open in Google Colab View on GitHub

Accessing List Elements by Position and Slicing 🔝

Python lists use zero-based indexing, so the first element is at position 0, 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.

Negative Indexing and List Slicing

Negative indexes can be used to access elements starting from the end of the list. We can also use slicing to extract a range of elements.
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']

Slicing Beyond the Last Position

While directly accessing an index beyond the available elements causes an error, a slice can safely extend beyond the end of the list. Python simply returns the available elements.
print(my_list[1:8])  # Index 8 is beyond the list, but slicing does not raise an error
Output
['John', 'King', 'Ravi', 'Alex']

Changing a List Item

Lists are mutable, so we can change an existing value by using its index.
my_list=['Alex','Ronald','John']

my_list[1]='Ravi'

print(my_list)
Output
['Alex', 'Ravi', 'John']

Displaying All List Items Using a Loop 🔝

We can use a for loop to access and display each item in a list one by one.
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.

Python List Methods 🔝

MethodDescription
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.

Searching for an Element Using in 🔝

The 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

Searching for a Pair of Numbers in a Nested List

A list can contain other lists as its elements. We can use the 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.

Using range() to Create a List 🔝

Create a list using a range of values starting at 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]

Using a String to Create a List 🔝

Using the 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']

Creating a List Using List Comprehension 🔝

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]

Unpacking List Elements 🔝

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(), max(), min() and Mean 🔝

The 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.
The 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

Finding the Mean of List Values

For a list of numbers, we can calculate the mean by dividing the 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

Using statistics.mean()

Python also provides the 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 of Elements in a List 🔝

A Python list is an iterable object. We can pass a list of numbers to the 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.

Collecting Matching Elements by Filtering 🔝

We can use the 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.

Simpler Way Using in

For this example, the in 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']

Creating a List with Unique Elements 🔝

A 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}

Converting the Set Back to a List

After removing the duplicate values, we can use 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.

Removing Duplicates While Keeping the Original Order

We can also use a for loop to remove duplicate values. This method keeps the elements in their original order.
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.

Finding Duplicate Elements in a List

The 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.

Frequency of Elements in a List 🔝

We can count how many times each value appears in a list by using a dictionary. The list item becomes the dictionary key, and its frequency becomes the value.
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)

Common Elements Between Two Lists 🔝

We can find common elements between two lists by converting them to sets and using the intersection operator &.
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.

Difference Between Two Lists 🔝

We can find the values present in one list but not in another by converting the lists to sets and using the difference operator -.
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.

Difference Without Removing Duplicates

If we want to keep the original order and duplicate values, we can use a list comprehension.
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.

Highest and Lowest Common Elements

We can first find the common values by using set intersection. Then we can use 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.

Converting a List to a String 🔝

We can combine the elements of a list to create a single string by using the 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 Element from a List 🔝

Python's 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.

2D List 🔝

A 2D list contains lists inside another list. We can access an item from each inner list by using its index. In this example, we create a new list using the second item from each inner list. Since list indexing starts from 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.

Searching for a Matching String Inside a 2D List 🔝

A 2D list contains several inner lists. We can loop through each inner list and use the 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.

Finding the First Matching Row Using next()

We can also get the first matching row in one statement by using 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.

Creating a List from JSON Data 🔝

We can read data from a JSON file and store selected values in a Python list. Here is the sample JSON file used in this example.
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.

Using List Comprehension

We can create the same list in one line by using list comprehension.
names=[student['name'] for student in data]

print(names)
This expression reads the name value from each student record and creates a new list.

Creating a List from Database Query Results 🔝

We can create a Python list from data returned by a database query. In this example, SQLite stores the database, and SQLAlchemy connects Python to the database. The query reads the table names from 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.

Python List Practice Questions 🔝

Python- Multi dimensional List Matrix Multiplication without using built-in functions List Comprehension split() to create List Python- List append Questions with solutions on List




Subscribe to our YouTube Channel here



plus2net.com







Python Video Tutorials
Python SQLite Video Tutorials
Python MySQL Video Tutorials
Python Tkinter Video Tutorials
We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles Contact us
©2000-2026   plus2net.com   All rights reserved worldwide Privacy Policy Disclaimer