Monday, June 19, 2023

Sequence in Python - Python List

 

SEQUENCES

 

Python List

python offers a range of compound datatypes often referred to as sequences. list is one of the most frequenty used and very versatile datatypes used in python.

J  List is Mutable

J  Mutable means we can change and reassign value of variable index

J  List is like Array

J  but Array store only similar datatype

J  but list stores different datatype

J  list index starts with 0

 

how to create a list?

  • In python programming , a list is create by placing all the item (elements)   inside a square bracket [  ],separated by commas.

 

  • It  can have any number of item  and they may be different types (integer, float, string etc.. ).

 

#empty list

list1= []

# list of integers

list1  = [20 , 12 , 43]

# list  with mixed datatypes

List1 = [2 , 4 , "hai" , 15.2 , 2+3j]

 

Also , a list can even have another list as an item . this is called nested  list

# nested list

 list1 = ["hai" , [4,3,96],['a','e','i','o','u']] 

 

 

LIST INDEX

list1  =  ['a','e','i','o','u']

print(List1 [0])

#output: a

 

print(list1[2])

#output:i

 

print(List1[4])

#output: u

 

#List1[4.0]

#Error! only integer can be used for indexing

 

#nested list

n_list = ["happy",[2,0,1,5]]

#Nested indexing

 

#output: a

print(n_list[0][1])

 

#output : 5

print(n_list[1][3])

 

Negative  indexing

 The index of -1 refers to thelast item, -2 to the second last item and so on.

list=['a','e','i','o','u']

print(list[-1])

print(list[-5])

OUTPUT

u

a

slice lists

list1=['p','y','t','h','o','n']

#element 3rd to 4th

print(list1[2:4])

Output:   ['t', 'h']

#elements begining to 4th

print(list1[:-5])

Output:  ['p']

#elements 5th to end

print(list1[4:])

Output:  ['o', 'n']

#elements begining to end

print(list1[:])

Output:   ['p', 'y', 't', 'h', 'o', 'n']

 

HOW TO CHANGE OR ADD ELEMENTS TO A LIST ?

num = [2,4,6,8]

#change the 1st item

num[0]=1

print(num)

 #output:  [1,4,6,8]

#change 2nd to 4th items

num[1:4] = [3,5,7]

print(num)

 #Output:  [1,3,5,7]

 Append() and extend() Method

oddnum=[1,3,5]

oddnum append(7)

print(oddnum)

oddnum.extend([9,11,13])

print(oddnum)

output

[1,3,5,7]

[1,3,5,7,9,11,13]

List  Concatenation

oddnum = [1,3,5]

print(oddnum + [9,7,5])

print(["yes"]*3)

 

output

[1,3,5,9,7,5]

['yes','yes','yes']

 Insert() Method

oddnum= [1,9]

oddnum.insert(1,3)

print(oddnum)

OUTPUT

[1,3,9]

oddnum[2:2]= [5,7]

print(oddnum)

OUTPUT

[1,3,5,7,9]

 

HOW TO DELETE OR REMOVE ELEMENTS FROM A LIST :

we can delete one or more items using del keyword.

list1=['p','r','o','b','l','e','m']

del list1[2]

print(list1)

 Output :   ['p','r','b','l','e','m']

del list1[1:5]

print(list1)

 Output: ['p','m']

print(list1)

 

output

['p','r','b','l','e','m']

['p','m']

traceback (most recent call last):

file"c:/python33/ss.py",line 17 , in<module>

print(list 1)

 

list1 = ['p','r','o','b','l','e','m']

list1.remove('p')

print(list1)

print(list1.pop(1))

print(list1)

print(list1.pop())

print(list1)

list1.clear()

print(list1)

 

 

output

['r','o','b','l','e','m']

o

['r','b','l','e','m']

m

['r','b','l','e']

[]

 

>>>list1 = ['p','r','o','b','l','e','m']

>>>list1[2:3] =[]

>>>list1

['p','r','b','l','e','m']

>>>list1[2:5]=[]

>>>list1

['p','r','m']

Python list methods

append()

Add an element to the end of the list

extend()

Add all elements of a list to the another list

insert()

Insert an item at the defined index

remove()

Removes an item from the list

pop()

Removes and returns an element at the given index

clear()

Removes all items from the list

index()

Returns the index of the first matched item

count()

Returns the count of number of items passed

sort()

Sort items in a list in ascending order

reverse()

Reverse the order of items in the list

copy()

Returns a shallow copy of the list

list1=[34,56,12,56,78,0,6,7,12]

print(list1.index(12))

print(list1.count(12))

list1.sort()

print(list1)

list1.reverse()

print(list1)

OUTPUT

2

2

[0,6,7,12,12,34,56,56,78]

[78,56,56,34,12,12,7,6,0]

List comprehension:Elegant way to create new list

list comprehension is an elegant and concise way to create new list from an existing list in python

list comprehension consists of an expression followed by for statement inside square brakets.

>>>odd=[x for x in range(20) if x % 2 ==1]

>>>odd

[1,3,5,7,9,11,13,15,17,19]

Other list operations in Python

List Membership Test

we can test if an item exists in a list or not,using the keyword in.

list1=['p','y','t,'h','o','n']

print('p' in list1)                #output:true

print('a' in list1)                #output:false

print('c' not in list1)         #output:true

Iterating through a List

using a for loop we can iterate though each item in a list.

for fruit in['apple','banana','mango']:

    print("i like",fruit)

OUTPUT

i like apple

i like banana

i like mango

Built-in functions with list

function

Description

all()

Return true if all elements of the list are true (or if the list is empty)

any()

Return  true if any elements of the list is true.if the list is empty,return false

enumerate()

Return an enumerate object.it contains the index and value of all the items of list as a tuple

len()

Return the length(the number of items)in the list

list()

Convert an iterable (tuple,string,set,dictionary)to a list

max()

Return the largest item in the list

min()

Return the smallest item in the list

sorted()

Return a new sorted list(does not sort the list itself)

sum()

Return the sum of all elements in the list

#empty list 'a'

>>>a=[]

#all() function return true if all elements are true or list is empty

>>>all(a)

True

>>>a.append(3)

>>>a.appened(4)

>>>a

[3,4]

>>>all(a)

True

>>>a.append(0)

#return false because one zero element added

>>>all(a)

false

#any() return true if any element of a list is true

#if list is empty return false

>>>a

[3,4,0]

>>>any(a)

True

>>>b=[]

>>any(b)

False

#example len() to count no of element in the list

>>>len(a)

3

>>>max(a)

4

>>>min(a)

0

#sorted return a new sorted list(does not sort the list itself)

>>>sorted (a)

[0,3,4]

#list remain unchanged

>>>d.sorted(a)

>>>d

[0,3,4]

>>>sum(a)

7

0 comments:

Post a Comment