LIST in Python


List is one of the four data types which are used to store multiple data using a single variable.
For comparison all four such data types are listed here.
... LISTTupleSetDictionary
MutableMutable ImmutableMutableMutable
indexyes
my_list[1]
yes
my_tuple[1]
NoYes
my_dict['key']
DuplicateYesYes NoNo ( key )
ChangeableYes No NoYes
Example['a','c','e']('a','x','y'){'a','c','f'}{'a':'one','b':'two','c':'three'}

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 data structure List tuple set and dictionary using List methods and functions

Using range to create list 🔝

Create one list using a range of values. It should start from 5 , stops before 50 with increment of 10.
x=range(5,50,10)
my_list=list(x)
print(my_list)
Output
[5, 15, 25, 35, 45]

List by using for loop with condition 🔝

my_list=[ r**2 for r in range(5)] # Square of the numbers 
## List of square of the even numbers 
my_list=[ pow(r,2) for r in range(5) if r%2==0]
print(my_list)

Unpacking and listing elements 🔝

my_list=[5,50,10]
for i in range(*my_list):
  print(i)
Output is
5
15
25
35
45
Read how list is used after unpacking to create a range
my_list=['Alex','Ronald','John']
print(*my_list)
Output
Alex Ronald John

Using string to create List 🔝

Using split() we can break a string. By default split() uses space as delimiter to break a string and returns a list.
str="Welcome to Python"
print(str.split())
Output
['Welcome', 'to', 'Python']

Displaying elements based on position 🔝

my_list=['Alex','Ronald','John']
print(my_list[2])
Output is here
John
The position starts from 0 and first element value is my_list[0], so the data at my_list[2] gives us John.
my_list=['Ronald','John','King','Ravi','Alex']
print(my_list[-1]) # last element will be displayed : Alex
print(my_list[-2]) # 2nd from last element will be displayed : Ravi
print(my_list[0:])  # All elements starting from 0 position till end.
print(my_list[:3])  # All elements starting from 0 position till 3.
print(my_list[1:4])  # All elements starting from 1 position till 4.
Output is here
Alex
Ravi
['Ronald', 'John', 'King', 'Ravi', 'Alex']
['Ronald', 'John', 'King']
['John', 'King', 'Ravi']
We can go beyond the last element ( No error here )
print(my_list[1:8])  # All elements starting from 1 position till end.
Output
['John', 'King', 'Ravi', 'Alex']

Displaying all items by looping 🔝

We used for loop to display all items of the list.
my_list=['Alex','Ronald','John']
for i in my_list:
    print(i)
Output is here
Alex
Ronald
John

Methods we can use with list. 🔝

Method Description
append(x) Add element x at the end of the list
clear() Removes all elements of the list
copy() Returns a copy of the list
count(x) Count the number of matching input value x present inside list
extend(iterable) Add one more list ( any iterable ) at the end
index(x) Returns the position of first matching element x
insert(i,x) Add element x at given position i
pop([i]) Removes element from given position i
remove(x) Remove the first matching element x
reverse() Reverse the sequence of elements
sort() Sort the list

Searching element using in 🔝

Read more on in.
my_list=['Alex','Ronald','John']
if 'John' in my_list:
  print("Yes, included ")
else:
  print("No, not included")
Output is here
Yes, included
Searching pair of numbers within a list
my_list=[[1,3],[3,4],[4,6]]
if [3,4] in my_list:
    print("yes present")
else:
    print("Not present")
output is here
yes present

Collecting matching elements by filtering 🔝

Create a list by filtering matching string only.
def my_check(x):
    if x.find('xy') <0: # check for string xy
        return False
    else:
        return True
list_source=['abcd.php','xyabcd','pqrxy','dataxy'] # sample list
list_filter=filter(my_check,list_source) # used filter 
print(list(list_filter))

len(), max() , min() 🔝

len() : Total Number of elements present in a list
my_list=['Alex','Ronald','John']
print("Number of elements:",len(my_list))
Output
Number of elements: 3
max() : Maximum value of elements present in a list
min() : Minimum value of elements present 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
We can get mean by dividing sum of values with number of elements.
print("Mean value : ", sum(my_list)/len(my_list)) # 5.0
We can import statistical module and use mean() in Python 3.4+
import statistics 
print("mean value : ",statistics.mean(my_list)) # 5
High School Python ( part of Syllabus)

Creating a list with distinct elements 🔝

We can use a set to store unique elements as set don't accept duplicate elements.
my_list=[1,2,3,4,4,5,5,6]
print(set(my_list))
Output
{1, 2, 3, 4, 5, 6}
Using this set we can create the list again.
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)
Removing duplicate by using for loop
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]
List of duplicate elements in a list
a = [1,2,3,2,1,5,6,5,5,5]
import collections
print([item for item, count in collections.Counter(a).items() if count > 1])
## [1, 2, 5]
Getting unique elements and counting the occurrence by using Counter.

Frequency of elements in a list 🔝

Counting the frequency of elements in a list using a dictionary.
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}
High School Python ( part of Syllabus)

Sum of elements of a list 🔝

As list is an iterator Object , we can use sum to calculate sum of all 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

Common elements between two Lists 🔝

list1=[3,2,5,8]
list2=[5,2,8,9]
print(set(list1) & set(list2))
Output
{8, 2, 5}

Difference between two lists 🔝

l1=[5,10,20,25,15,10,5]
l2=[20,10]
l3=list(set(l1)-set(l2)) # removes the duplicates 

#Checks all elements by looping and without removing duplicates
#l3=[i for i in l1 + l2 if i not in l1 or i not in l2]

print(l3)
Highest and lowest Common elements
print(max(set(list1) & set(list2)))
print(min(set(list1) & set(list2)))
Output
8
2

From List to String 🔝

We can create a string by using all elements of a list. While creating string if any integer ( or other type of data ) is there then we will get an error message. So we used map() to convert all elements to string object before using join() to join them.
my_list = ['One',2,'Three']       
my_str=",".join(map(str,my_list))
print(my_str)
map() to apply function or lambda to each element of a list

Creating a list by using data from JSON file 🔝

Here is the sample JSON file.
import json
path="D:\\my_data\\student.json" # use your sample file. 
fob=open(path,)
data=json.load(fob)
names=[]
for student in data:
    #print(student['name'])
    names.append(student['name'])
print(names)
fob.close()
Using one line for loop in above code.
names=[r['name'] for r in data]

Random element from List 🔝

import random
my_list=['Alex','Ron','Ravi','Geek','Rbindra']
random_element = random.choice(my_list)
print(random_element)

2D List 🔝

Create one List using all the 2nd item of each inner List
l1=[['abc','def','ghi','jkl'],
    ['mno','pkr','frt','qwr'],
    ['asd','air','abc','zpq'],
    ['zae','vbg','qir','zab']]
my_name=[r[1] for r in l1]
print(my_name)# Output is : ['def', 'pkr', 'air', 'vbg']

Searching for matching string inside 2D list 🔝


l1=[['abc','def','ghi','jkl'],
    ['mno','pkr','frt','qwr'],
    ['asd','air','abc','zpq'],
    ['zae','vbg','qir','zab']]
for r in l1:
    if 'pkr' in r:
        print(r) 
Output
['mno', 'pkr', 'frt', 'qwr']
We will get same output by using this one-liner
my_row = next((r for r in l1 if 'pkr' in r), None)
print(my_row)

Getting a list from data returned from database table 🔝

This code connects to a SQLite database using SQLAlchemy, retrieves all table names from the database schema, and stores them in a Python list. It uses the SQL query SELECT name FROM sqlite_master WHERE type = 'table' to fetch the names of all tables. A list comprehension is employed to extract each table name from the query result and organize it into a list, which is then printed.
from sqlalchemy import create_engine, text

# Assuming my_conn is a connection to your database
# Replace 'sqlite:///your_database.db' with your actual database connection string
engine = create_engine('sqlite:///your_database.db')
my_conn = engine.connect()

# Query to fetch table names from SQLite database
r_set = my_conn.execute(text("SELECT name FROM sqlite_master WHERE type = 'table'"))

# Create a list from the query result
table_names = [row[0] for row in r_set]

# Output the list
print(table_names)

Questions 🔝

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


Subhendu Mohapatra — author at plus2net
Subhendu Mohapatra

Author

🎥 Join me live on YouTube

Passionate about coding and teaching, I publish practical tutorials on PHP, Python, JavaScript, SQL, and web development. My goal is to make learning simple, engaging, and project‑oriented with real examples and source code.



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-2025   plus2net.com   All rights reserved worldwide Privacy Policy Disclaimer