... | LIST | Tuple | Set | Dictionary |
---|---|---|---|---|
Mutable | Mutable | Immutable | Mutable | Mutable |
index | yes my_list[1] | yes my_tuple[1] | No | Yes my_dict['key'] |
Duplicate | Yes | Yes | No | No ( key ) |
Changeable | Yes | No | No | Yes |
Example | ['a','c','e'] | ('a','x','y') | {'a','c','f'} | {'a':'one','b':'two','c':'three'} |
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']
x=range(5,50,10)
my_list=list(x)
print(my_list)
Output
[5, 15, 25, 35, 45]
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)
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
str="Welcome to Python"
print(str.split())
Output
['Welcome', 'to', 'Python']
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']
my_list=['Alex','Ronald','John']
for i in my_list:
print(i)
Output is here
Alex
Ronald
John
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 |
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
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()
: 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 listmin()
: 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
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.
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}
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
list1=[3,2,5,8]
list2=[5,2,8,9]
print(set(list1) & set(list2))
Output
{8, 2, 5}
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
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
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]
import random
my_list=['Alex','Ron','Ravi','Geek','Rbindra']
random_element = random.choice(my_list)
print(random_element)
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']
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)
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)