2. List Basics * Copying Lists ,
Passing List to Functions * Returning
a List from function * Searching Lists
* Multidimensional Lists * Tuples *
Sets * Comparing Sets and Lists *
Dictionaries.
K.ANGURAJU AP / CSE
3. List Basics
CREATING A LIST / DEFINE LIST.
• A list contains items separated by commas and
enclosed with square bracket [ ] .
• List holds heterogeneous values
• List and arrays are same in python.
• values stored in list is accessed by using its index or its
value by slicing.
Syntax
List_name= [ value1, value2 …. Value n]
Example 1:
>>> List=[“ram”,31,54,12,47]
>>> list
[“ram”,31,54,12,47]
K.ANGURAJU AP / CSE
4. Example - 2:
colours = ['red', 'blue', 'green']
print colours[0] ## red
print colours[2] ## green
print len(colours) ## 3
K.ANGURAJU AP / CSE
5. Accessing values in lists
To access values in a list by using square
bracket [ ] , with the index 0,1,2 …. N, List is
accessed by using positive or negative
indexing.
positive indexing starting form 0,1,2,…. n
Negative indexing starting from -1, -2, -3
……-n
There are two methods available in list to access
the list data:
1.by using slices
2.by using indexes. K.ANGURAJU AP / CSE
6. By using indexes:
By using square bracket with index value to
access the list elements, here the index starts
from 0
Example:
list1=[‘ram’ , ‘ kumar’]
print ( list1[0])
Print( list2[1])
output:
[‘ram’]
[‘kumar’]
7. By using List slices:
We can also access the list element by
using slice method; here we access the
specific elements from the list.
Slice syntax:
list variable name[ starting index : stop
index – 1 ]
9. UPDATING A LIST:
Lists are mutable, which means the
elements in the list are updatable.
We can update it by using its index
position with square bracket.
Also to add a new entry within existing
entry.
11. Using slice operation we can update more than
one value in the list.
>>>list[1:3]=[‘strawberry’, ‘pomegranate’]
>>>print(list)
Output:
[ ‘Watermelon’ , ’strawberry’ , ‘pomegranate’ ,
’grapes’]
12. Deleting a list
Deletion is the process of deleting an
element from the existing list,
Deletion removes values from the list.
To delete the list element in two ways.
• By using del keyword
• By using pop() function.
13. By using del keyword
Examples
>>>List=[‘watermelon’, ’orange’, ’mango’,
‘pineapple’]
del list[0]
print(list)
Output:
[’orange’, ’mango’, ‘pineapple’]
14. To delete by using slice :
List=[’orange’, ’mango’, ‘pineapple’]
del list[1:3]
print(list)
Output:
[‘orange’]
15. By using pop() method
list . pop(index)
pop () is one of the list method ,it Removes and returns those
element at the given index
List=[1,2,3,4,5]
List.pop(4) #index
5
Print(list)
[1,2,3,4]
16. List is a sequence type
List and string’s are sequence type in
python.
A string is a sequence of character
While List also having sequence of
elements.
those sequence to be accessed by for loop
and set of basic function.
18. For loop - Traverse the element from left to
right
<, >, <=, >=, = - Used to compare two list
+ - s1+s2 - concatenate two sequence
19. Comparing List
List are compared by using (<, >, <=, >=, = )
Operator’s
Example:
A=[1,2,3]
B=[1,2,3]
>>>A==B
True
>>>A!=B
False
20. Traverse Elements in a for Loop
A loop is a block of code that repeats itself
until a certain condition satisfied. Here we use
the simple for loop to print all the content
with in the text file.
Example:
Ice_cream=[‘vanilla’, ’chocolate’,’ strawberry’]
for i in ice_cream :
print(i)
OUTPUT:
vanilla
chocolate
strawberry
21. List Loop (using range function)
The range() function returns sequence of
integers between the given start integers to
the stop integers
Syntax:
range(start, stop, step)
example
A=[10,20,30,40]
for i in range(0,4,1):
print(a[i])
22. List operators
List having more operation like string ( ‘ + ‘
and ‘ * ‘ ), that is concatenation, in and not in
Following basic operation performed in list:
Concadenation (+)
Repetation (*)
Membership (in)
K.ANGURAJU AP / CSE
23. Expression Results Description
[1,2,3,4]+[5,6] [1,2,3,4,5,6]
Concatenation is the process of
combine two list elements (+)
[‘hi’]*2 [‘hi’,’hi’]
To repeat the list elements in
specified number of time
(Repetition)
2 in [1,2,3] True
Membership – To find specified
elements is in the list or not
K.ANGURAJU AP / CSE
24. List methods
• Python has a number of built-in data
structures in list.
• These methods are used as a way to organize
and store data in the list.
• Methods that are available in list are given
below
• They are accessed as list.method()
K.ANGURAJU AP / CSE
25. Methods Description
Append()
Add an element to the end of the list
Extend()
Add all the element of the list to the another list
Insert()
Insert an element at the defined index
Remove()
Removes an element from the list
Pop()
Removes and returns an element at the given
index
Clear()
Removes all the element from the list
Index()
Returns the list of the matched element
Count()
Returns the number of times the element present
in the list
Sort()
Sort the element in ascending order
Reverse()
Reverse the order of the element in the list
Copy()
Copy the elements in the list
K.ANGURAJU AP / CSE
26. Append()
list.append(element )
append() is one of the list method , It will add a single element to
the end of the list.
Example:
List=[1,2,3,4,5]
List. append(6)
Print(list)
Output:
[1,2,3,4,5,6]
Insert()
list. insert(index, element)
insert () is one of the list method ,it inserts the element at the
specified index.
Example:
List=[1,2,3,4,5]
List. insert(4,7)
Print(list)
Output:
[1,2,3,4,7,5] K.ANGURAJU AP / CSE
27. Extend() – list1 . extend(list2)
Extend () is one of the list method ,it Add all the element of
the one list to the another list.
aList = [123, 'xyz', 'zara', 'abc', 123];
bList = [2009, 'mani'];
aList.extend(bList)
print ("Extended List : ", aList )
Extended List : [123, 'xyz', 'zara', 'abc', 123, 2009, 'mani']
POP()
list . pop(index)
pop () is one of the list method ,it Removes and returns those
element at the given index
List=[1,2,3,4,5]
List.pop(4) #index
5
Print(list)
[1,2,3,4]
K.ANGURAJU AP / CSE
28. Index()- list . Index(element)
index () is one of the list method ,it Returns
the index position of the matched element.
List=[1,2,3,4,5]
List.index(4)
Output: 3 #index
COPY()- list2 = list1.copy()
copy () is one of the list method ,it Copy the
elements from the one list and assign into a new
list.
List1=[1,2,3,4,5]
list2=List1.copy()
Print(list2)
Output: [1,2,3,4,5]
K.ANGURAJU AP / CSE
29. Reverse()-
reverse () is one of the list method ,it Reverse
the order of the element in the list
List=[1,2,3,4,5]
list.reverse()
Print(list)
Output: [5,4,3,2,1]
Count()-
count () is one of the list method ,it Returns
the number of times the element present in the list.
List=[1,2,3,4,5]
List.count(5)
Print(list)
Output: 1 K.ANGURAJU AP / CSE
30. Sort()- sort () is one of the list method ,it Sort
the element in ascending order
List=[4,7,2,3]
List.sort()
Print(list)
Output: [2,3,4,7]
Clear()- clear() is one of the list method ,it
Removes all the element from the list
List=[1,2,3,4]
List.clear()
Print(list)
Output: none
K.ANGURAJU AP / CSE
31. Remove() - list.remove(element)
remove () is one of the list method ,it
Removes the specified element from the list
List=[1,2,3,4,5]
List.remove(4) #element
Print(list)
Output: [1,2,3,5]
K.ANGURAJU AP / CSE
32. Copying List
Copying the data in one list to another list
You can copy individual elements from the
source list to target list.
By using assignment operator to copy the
one list element to another list.
Syntax:
Destination list =Source list
34. LIST LOOP
we can possible to apply looping statements
into list , to access the list elements
A loop is a block of code that repeats itself
until a certain condition satisfied.
It avoid the complexity of the program.
Example program:
Ice_cream=[‘vanilla’, ’chocolate’,’ strawberry’]
for i in ice_cream :
print(i)
OUTPUT:
vanilla
chocolate
strawberry
35. Passing Lists to Function
• Passing list as a function arguments is called
as list parameter.
• Actually it passes a reference to the list, not a
copy of the list.
• Since list are mutable changes made in
parameter it will change the actual argument.
37. Returning a List from function
The function call send list of data to
function definition.
also the function definition return the
resultant list to corresponding function call is
called returning a list from a function
38. Searching List
Searching is the process of looking for a
specific element in a list.
In this we search the individual element
from the list by using indexes.
There are two methods to search the
elements.
1. Linear Search
2. Binary Search
39. #Linear Search program
a=[0,0,0,0,0,0,0,0,0,0]
s=0
n=int (input("enter the number of element:"))
print("enter the",n," numbers")
for i in range(0,n,1):
a[i]=int (input())
s_element=int ( input("enter the searching element:"))
for i in range(0,len(a),1):
while(a[i]==s_element):
print("the element is found:", a[i])
s=1
break
If(s==0):
print(“The element is not found”)
43. Write a python program to sort the given list
elements by using selection sort
A=[0,0,0,0,0,0,0,0]
n=int (input("enter the n value"))
print("Enter the list element")
for i in range(0,n,1):
A[i]=int (input())
print(A)
44. for i in range(0, len(A) ,1):
fillslot = i
for j in range(i+1, len(A),1):
minpos=j
if (A[fillslot] >= A[minpos]):
temp =A[fillslot]
A[fillslot]=A[minpos]
A[minpos]=temp
print("sorted list elements are", A)
45. Output:
enter the n value5 Enter the list element
19 2 3 5 6
[19, 2, 3, 5, 6, 0, 0, 0]
Sorted list elements are [0, 0, 0, 2, 3, 5, 6, 19]
46. Multidimensional list
Data in a table or a matrix can be stored in
a two dimensional list.
The value in a two dimensional list can be
accessed through a row and column indexes.
Here the data stored in row wise as well as
data accessed using row and column indexes.
Example:
A=[ [ 1,2],
[2,3] ]
47. TUPLE
• Tuple contains items separated by commas and
enclosed with parenthesis().
• Values cannot be edit or update and insert a new
value in Tuple.
• The values in tuples can be stored any type.
• Tuples are immutable.
Example:
>>>tuple=(10,20,30,’dhoni’,’K’,)
>>>print(tuple)
(10,20,30,’dhoni’,’K’,)
48. Tuple elements are accessed by using it’s indexes
with [] ,also accessed using slices
Print values by using index:
>>>tuples=(‘a’, ’b’, ’c’, ’d’)
>>>print(tuples[0])
output: a
Print values by using slicing:
>>> print(tuples[1:3])
output: (‘b’, ’c’)
If we change values of a tuple it shows:
tuples[0]=‘z’
output: Error: object does not support item
assignment
49. TUPLE ASSIGNMENT:
To define a tuple we should assign more than
one values or one element with comma.
>>>t1=(‘a’)
>>>print(t1)
>>>a
Type(t1)
<class 'str'>
>>>t1=(‘a,’)
>>>print(t1)
>>>a
Type(t1)
<class ‘tuple'>
51. Assign tuple values into a variable by using index:
>>>m=(‘hai’, ‘hello’)
>>>x=m[0]
>>>y=m[1]
>>>x
‘hai’
>>>y
‘hello’
Assign tuple values into multiple variable:
>>>m=(‘hai’, ‘hello’)
>>>(x,y)=m
>>>x
‘hai’
>>>y
‘hello’
52. Swapping
To swap two number we need temporary
variable in normal swapping .
For example, to swap a and b
>>>a=10; b=20
>>>temp = a
>>>a = b
>>>b = temp
The tuple assignment allows us to swap
the values of two variables in a single
statement.
>>>(a, b) = (b, a)
53. Tuple as return values
• A normal function can only return one value, but
the effect of tuple functions returning multiple
values.
• For example, if you want to divide two integers
and compute the quotient and remainder, it is
inefficient to compute x/y and then x%y.
• The built-in function divmod takes two
arguments and returns a tuple of two values, the
quotient and remainder.
55. Tuple predefined function
• len() – provide number of item present in the tuple
Example:
a=(1,2,3,4)
print(len(a))
Output:
4
• min() – this function return minimum number in a
tuple
Example:
a=(1,2,3,4)
print(min(a))
Output:
1
56. • max() - this function return maximum number in a
tuple
Example:
a=(1,2,3,4)
print(max(a))
Output:
4
• sum() – this function sums the individual item
Example:
a=(1,2,3,4)
print(sum(a))
Output:
10
57. • Count() - it returns number of time repeated count of specified
element.
Example:
a=(1,2,3,4)
print(a.count(4))
Output:
1
• cmp() – This check the given tuple are same or not, if both same it
return zero(0), if the first tuple big then return 1, Otherwise return
-1
Example:
t1=(1,2,3,4)
t2=(1,2,3,4)
print(cmp(t1,t2)
Output:
0
58. SETS IN PYHTON
Lists and tuples are standard Python data
types that store values in a sequence.
Sets are another standard Python data
type that also store values.
The major difference is that sets, unlike
lists or tuples, cannot have multiple
occurrences of the same element
And store unordered values.
59. Because sets cannot have multiple
occurrences of the same element,
it makes sets highly useful to efficiently
remove duplicate values from a list or tuple
and to perform common math operations
like unions and intersections.
60. Initialize a Set
you can initialize an empty set by using set().
Example:
emptySet = set()
61. To initialize a set with values, you can pass in a
list to set().
>>> dataEngineer = set(['Python', 'Java', 'Scala',
'Git', 'SQL', 'Hadoop'])
>>> dataEngineer
{'Hadoop', 'Scala', 'Java', 'Git', 'SQL', 'Python'}
If you look at the output of dataEngineer
variables above, notice that the values in the
set are not in the order added in. This is
because sets are unordered.
62. Sets containing values can also be
initialized by using curly braces.
>>> dataEngineer = {'Python', 'Java', 'Scala', 'Git',
'SQL', 'Hadoop'}
>>> dataScientist = {'Python', 'R', 'SQL', 'Git',
'Tableau', 'SAS'}
Output:
>>> dataEngineer
{'Scala', 'SQL', 'Java', 'Git', 'Hadoop', 'Python'}
63. Difference between set and list
List :
The list is a data type available in Python
which can be written as a list of comma-
separated values (items) between square
brackets.
List are mutable .i.e it can be converted
into another data type and can store any data
element in it.
List can store any type of element.
64. SETS:
Sets are an unordered collection of
elements or unintended collection of items In
python.
Here the order in which the elements are
added into the set is not fixed, it can change
frequently.
It is defined under curly braces{}
Sets are mutable, however, only
immutable objects can be stored in it.
65. Dictionaries
• Python’s dictionaries are kind of hash-table type
• They work like associative arrays or hashes found
in Perl and consist of key-value pairs.
• A dictionary key can be almost any Python type,
but are usually numbers or strings.
• Dictionaries are enclosed by curly braces ({ }) and
values can be assigned and accessed using
square braces ([]).
66. a = {‘name’: ‘john’,‘code’:6734, ‘dept’: ‘sales’}
print (a) # Prints complete dictionary
print (a.keys()) # Prints all the keys
print (a.values()) # Prints all the values
This produces the following result-
{‘name’: ‘john’, ‘code’:6734, ‘dept’: ‘sales’}
[‘dept’, ‘code’, ‘name’]
[‘sales’, 6734, ‘john’]
67. Accessing values in a dictionary
To access dictionary elements, you can use
the familiar square brackets along with the key
to obtain its value.
There are two methods available in
dictionary to access the dictionary data:
By using slices
By using keys.
By using Keys:
By using square bracket with Key value to
access the dictionary elements
69. Updating a dictionary:
Dictionary is also mutable,
which means the elements in the
dictionary are updatable.
We can update it by using its key with
square bracket.
Also to add a new entry within existing
entry.
We can update a dictionary by adding a
new entry or modifying an existing entry, or
deleting an existing entry.
71. Adding new entry
To add a new entry within the existing
dictionary by using the its index position to
assign dictionary element .
Example:
friends = { “name” : “ram” , “age” : 18 ,
“address”: “trichy” }
friends [ 3 ] = { “mobile number” : 0123456789 }
print ( friends )
Output:
{ “name” : “ram” , “age” : 18 , “address”:
“trichy” , { “mobile number” : 0123456789 }}
72. Deleting element in a dictionary
Deletion is the process of deleting an
element from the existing dictionary; Deletion
removes values from the dictionary. To delete
the dictionary element in two ways.
By using del keyword
By using pop() function.
By using del keyword
Example:
friends = { “name” : “ram” , “age” : 18 ,
“address”: “trichy” }
del friends[0]