LIST in Python


Youtube Live session on Tkinter

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 )
ChangebleYes 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 incrment of 10.
x=range(5,50,10)
my_list=list(x)
print(my_list)
Output
[5, 15, 25, 35, 45]

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

Add , remove , update elements

Here is are 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

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]
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 error message we will get. 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)
Python- Multi dimensional List Matrix Multiplication without using built-in functions split() to create List Python- List append Questions with solutions on List


Subscribe to our YouTube Channel here


Subscribe

* indicates required
Subscribe to plus2net

    plus2net.com



    Post your comments , suggestion , error , requirements etc here





    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 FORUM . Contact us
    ©2000-2024 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer