Introduction to python
Introduction to python
Programming Unit 2
Akshata S. Bhayyar
Assistant Professor, Dept. of CSE,
MSRIT
LIST
A list is an ordered set of values, where each
value is identified by an index
The values that make up a list are called its
elements.
Also called as sequences
LIST VALUES
Ways to create a new list
enclose the elements in square brackets [ ]:
1.append()
syntax
list.append (element)
insert()
syntax
list.insert(position,
element)
extend()
syntax
List1.extend(List2)
[1, 2, 3, 2, 3, 4, 5]
[2, 3, 4, 5, 1, 2, 3, 2, 3, 4, 5
List Methods
sum()
syntax
sum(List)
List Methods
count()
syntax
List.count(element)
4
List Methods
Length()
syntax
len(list_name)
10
List Methods
index()
syntax
List.index(element[,start[,end]
])
1
List Methods
Deletion of List Elements
To Delete one or more elements, i.e. remove
an element, many built-in functions can be
used, such as pop() & remove() and
keywords such as del.
pop()
The index is not a necessary parameter, if
not mentioned takes the last index.
Syntax:
list.pop([index])
List Methods
List Methods
reverse()
1
List Methods
Sort( )
Pure functions and Modifiers
Pure functions : It does not modify any of
the objects passed to it as arguments and it
has no side effects, such as displaying a value
or getting user input.
>>> t1 = (’a’,)
• Without the comma, Python treats (’a’) as a string
in parentheses:
Tuple
If we try to modify one of the elements of
the tuple, we get an error:
Tuple packing and
unpacking
Tuple packing is nothing but the creation of
tuple, whereas tuple unpacking means to
extract tuple values and store them in individual
variables.
Tuple assignment
Tuple assignment
Tuples as return values
Functions can return tuples as return values
Composability of Data
Structures
Tuples items can themselves be other tuples.
Dictionary
Dictionaries
In a dictionary, the indices are called keys, so
the elements are called key-value pairs.
One way to create a dictionary is to start
with the empty dictionary and add elements.
The empty dictionary is denoted {}
Dictionaries
Dictionaries
nother way to create a dictionary
print(len(Subjects)
)
Dictionary operations
1. The del statement removes a key-
value pair from a dictionary
2.
print(len(Subjects))
Dictionary methods
A method is similar to a function, it
takes arguments and returns a value
but the syntax is different.
print(Subjects.keys())
dict_keys([2, 3, 4])
Dictionary methods
The items method returns both, in the
form of a list of tuples—one for each
key-value pair:
print(Subjects.items())