Python DataTypes
Python DataTypes
• Example
# Creating Blank List
List = []
print("Blank List: ")
print(List)
• Output
Blank List:
[]
• Example • Example
# Creating a List of numbers # Creating a List of
List = [10, 20, 14] strings and accessing
print("\nList of numbers: ") # using index
print(List) List = ["Green", "For", "Gorge"]
• Output print("\nList Items: ")
List of numbers:
print(List[0])
[10, 20, 14]
print(List[2])
• Output
List Items
Green
Gorge
• Example
# Creating a Multi-Dimensional List
# (By Nesting a list inside a List)
List = [['Green', 'For'] , ['Trees']]
print("\nMulti-Dimensional List: ")
print(List)
• Output
Multi-Dimensional List:
[['Green', 'For'], ['Trees']]
• Accessing elements from the List • Example
• In order to access the list items refer to #Creating a Multi-Dimensional List
the index number. Use the index operator # (By Nesting a list inside a List)
[ ] to access an item in a list. The index
must be an integer. Nested lists are List = [['Green', 'For'] , ['George']]
accessed using nested indexing. print("Accessing a element from
a Multi-Dimensional list")
• Example print(List[0][1])
• List = ["Green", "For", "George"] print(List[1][0])
• print("Accessing a element from Output
the list") Accessing a element from a Multi-
Dimensional list
• print(List[0])
For
• print(List[2])
George
• Output
Accessing a element from the list
Green
George
• Knowing the size of List
• Example
# Creating a List
List1 = []
print(len(List1))
• Output:
0
3
• Adding Elements to a List
• Using append() method
Elements can be added to the List by using the built-in append() function. Only one element
at a time can be added to the list by using the append() method, for the addition of multiple
elements with the append() method, loops are used. Tuples can also be added to the list with
the use of the append method because tuples are immutable. Unlike Sets, Lists can also be
added to the existing list with the use of the append() method.
• Example
List = []
print("Initial blank List: ")
print(List)
• Output
Initial blank List:
[]
• Example 2
List.append(1)
List.append(2)
List.append(4)
print("\nList after Addition of Three elements: ")
print(List)
• output
List after Addition of Three elements:
[1, 2, 4]
# Addition of List to a List
List2 = ['Red', 'Green']
List.append(List2)
print("\nList after Addition of a List: ")
print(List)
• Output
List after Addition of a List:
[1, 2, 4, ['Red', 'Green']]
• Using insert() method
• append() method only works for the addition of elements at the end of the
List, for the addition of elements at the desired position, insert() method is
used. Unlike append() which takes only one argument, the insert() method
requires two arguments(position, value).
# Creating a List
List = [1,2,3,4]
print("Initial List: ")
print(List)
• Output
• Initial List:
• [1, 2, 3, 4]
# Addition of Element at
# specific Position
# (using Insert Method)
List.insert(3, 12)
List.insert(0, 'Green')
print("\nList after performing Insert Operation: ")
print(List)
• output
• List after performing Insert Operation:
• ['Green', 1, 2, 3, 12, 4]
• Using extend() method
• Other than append() and insert() methods, there’s one more method for the Addition of
elements, extend(), this method is used to add multiple elements at the same time at the end of the list.
Note – append() and extend() methods can only add elements at the end.
• Example
# Creating a List
List = [1,2,3,4]
print("Initial List: ")
print(List)
List.extend([8, 'Green', 'Always'])
print("\nList after performing Extend Operation: ")
print(List)
• Output
Initial List:
[1, 2, 3, 4]
• output
• List after Removing a range of elements:
• [7, 8, 9, 10, 11, 12]
2.Using pop() method
• Pop() function can also be used to remove and return an element from the set, but by default it removes only the
last element of the set, to remove an element from a specific position of the List, the index of the element is passed
as an argument to the pop() method.
• Example
List = [1,2,3,4,5]
List.pop()
print("\nList after popping an element: ")
print(List)
List.pop(2)
print("\nList after popping a specific element: ")
print(List)
• Output
List after popping an element:
[1, 2, 3, 4]
apply a particular function passed in its argument to all of the list elements stores the
reduce()
intermediate result and only returns the final summation value
ord() Returns an integer representing the Unicode code point of the given Unicode character
cmp() This function returns 1 if the first list is “greater” than the second list
any() return true if any element of the list is true. if the list is empty, return false
apply a particular function passed in its argument to all of the list elements returns a
accumulate()
list containing the intermediate results
returns a list of the results after applying the given function to each item of
map()
a given iterable
This function can have any number of arguments but only one expression, which is
lambda()
evaluated and returned.
Tuples
• A tuple in Python is similar to a list.
• A Tuple is immutable. we cannot change the elements of a tuple once it is
assigned whereas we can change the elements of a list.
• Creating a Tuple
A tuple is created by placing all the items (elements) inside parentheses (),
separated by commas. The parentheses are optional, however, it is a good
practice to use them.
A tuple can have any number of items and they may be of different types
(integer, float, list, string, etc.).
• Examples • Output
# Empty tuple ()
my_tuple = () (1, 2, 3)
print(my_tuple) (1, 'Hello', 3.4)
('mouse', [8, 4, 6], (1, 2, 3))
# Tuple having integers
my_tuple = (1, 2, 3)
print(my_tuple)
# nested tuple
• Creating a tuple with one element is a bit tricky.
• Having one element within parentheses is not enough. We will need a trailing
comma to indicate that it is, in fact, a tuple.
my_tuple = ("hello")
print(type(my_tuple))
# Parentheses is optional
my_tuple = "hello",
print(type(my_tuple)) # <class 'tuple'>
• <class 'str'>
• <class 'tuple'>
• <class 'tuple'>
• A tuple can also be created without using parentheses. This is known as tuple
packing.
• Example
my_tuple = 3, 4.6, "dog"
print(my_tuple)
print(my_tuple[0]) # 'p'
print(my_tuple[5]) # 't'
# nested tuple
n_tuple = ("mouse", [8, 4, 6], (1, 2, 3))
# nested index
print(n_tuple[0][3]) # 's'
print(n_tuple[1][1]) # 4
• Output
• 2. Negative Indexing • 3. Slicing
• Python allows negative indexing for its • We can access a range of items in
sequences. a tuple by using the slicing
• The index of -1 refers to the last item, -2 operator colon :
to the second last item and so on. • my_tuple =
• Example ('p','r','o','g','r','a',
'm','i','z')
my_tuple = ('p', 'e', 'r', 'm', 'i',
't') •
print(my_tuple[-1]) • print(my_tuple[1:4])
print(my_tuple[-6]) •
• Output • print(my_tuple[:-7])
t • Output
p ('r', 'o', 'g')
('p', 'r')
• Changing a Tuple
• Unlike lists, tuples are immutable. But, if the element is itself a mutable data type like a list,
its nested items can be changed.
• We can also assign a tuple to different values (reassignment).
• Examples
• my_tuple = (4, 2, 3, [6, 5])
• my_tuple[1] = 9
# This statement error as TypeError: 'tuple' object does not support
item assignment
my_tuple[3][0] = 9
print(my_tuple)
my_tuple = ('p', 'r', 'o', 'g', 'r', 'a', 'm', 'i', 'z')
print(my_tuple)
• output
(4, 2, 3, [9, 5])
• Deleting a Tuple
• As discussed above, we cannot change the elements in a tuple. It means that we cannot
delete or remove items from a tuple.
• Deleting a tuple entirely, however, is possible using the keyword del
• Example
• my_tuple = ('p', 'r', 'o', 'g', 'r', 'a', 'm', 'i', 'z')
• del my_tuple[3]
# Above statement gives error as TypeError: 'tuple'
object doesn't support item deletion
del my_tuple
print(my_tuple)
• Output
Traceback (most recent call last):
File "<string>", line 12, in <module>
NameError: name 'my_tuple' is not defined
• Finding Length of a Tuple
• Example
tuple2 = ('python', 'Prog')
print(len(tuple2))
• Output
2
print(my_tuple.count('p'))
print(my_tuple.index('l'))
• output
2
3
Tuple Membership Test
• We can test if an item exists in a tuple or not, using the keyword in.
• Example
• my_tuple = ('a', 'p', 'p', 'l', 'e',)
•
• print('a' in my_tuple)
• print('b' in my_tuple)
• print('g' not in my_tuple)
• Output
True
False
True
• Using max() , min()
• Python tuple method max() returns the elements from the tuple with
maximum value.
• Python tuple method min() returns the elements from the tuple with
minimum value.
• Example
• t1=(1,2,3)
• t2=(4,5,6,7)
• print(max(t1))
• print(min(t1))
• Output
•3
•1
Set
• A Set is an unordered collection data type that is iterable. Since sets are
unordered, we cannot access items using indexes like we do in lists.
• mutable and has no duplicate elements.
• Python’s set class represents the mathematical notion of a set.
• The major advantage of using a set, as opposed to a list, is that it has a highly
optimized method for checking whether a specific element is contained in the
set.
• Sets can also be used to perform mathematical set operations like union,
intersection, symmetric difference, etc.
• set cannot have duplicate • set cannot have mutable
• Example items
• my_set = {1, 2, 3, 4, 3, 2} • Example
• print(my_set) my_set = {1, 2, [3, 4]}
• Output
{1, 2, 3, 4} • Output (Error)
• Traceback (most recent
call last):
• make set from a list File "<string>", line
• Example 15, in <module>
my_set = {1, 2, [3,
my_set = set([1, 2, 3, 2]) 4]}
print(my_set) TypeError: unhashable type
• Output : 'list'
{1, 2, 3}
• Creating Python Sets
• A set is created by placing all the items (elements) inside curly braces {}, separated
by comma, or by using the built-in set() function.
• It can have any number of items and they may be of different types (integer, float,
tuple, string etc.).
• But a set cannot have mutable elements like lists, sets or dictionaries as its elements.
• Example
• my_set = {1, 2, 3}
• print(my_set)
•
• # set of mixed datatypes
• my_set = {1.0, "Hello", (1, 2, 3)}
• print(my_set)
• Output
• Creating an empty set is a bit tricky.
Empty curly braces {} will make an empty dictionary in Python. To make a set
without any elements, we use the set() function without any argument.
• Example1
• a = {}
• print(type(a))
• Output
<class 'dict'>
• Example2
a = set()
print(type(a))
• Output
<class 'set'>
• Methods for Sets
• Adding elements With add() method
• Insertion in set is done through set.add() function, if member is not present
and inserted where an appropriate record value is created to store in the hash
table.
• We can add a single element using the add() method
s1 == s2 s1 is equivalent to s2
s1 != s2 s1 is not equivalent to s2
s1 <= s2 s1 is subset of s2
s1 >= s2 s1 is superset of s2
all() Returns True if all elements of the set are true (or if the set is empty).
any() Returns True if any element of the set is true. If the set is empty, returns False.
Returns an enumerate object. It contains the index and value for all the items of the set as
enumerate()
a pair.
sorted() Returns a new sorted list from elements in the set(does not sort the set itself).
# using dict()
my_dict = dict({1:'apple', 2:'ball'})
• While indexing is used with other data types to access values, a dictionary
uses keys. Keys can be used either inside square brackets [] or with
the get() method.
• If we use the square brackets [], KeyError is raised in case a key is not
found in the dictionary. On the other hand, the get() method
returns None if the key is not found.
•
•
•
• Examples
• Output
Jack
26
None
Traceback (most recent call last):
File "<string>", line 15, in <module>
print(my_dict['address'])
KeyError: 'address'
• Examples
Dict = {1: 'Green', 2: 'For', 3:{'A' : 'Welcome', 'B' : 'To',
'C' : 'Germany'}}
• print(Dict)
• OutPut
{1: 'Green', 2: 'For', 3: {'A': 'Welcome', 'B': 'To', 'C':
'Germany'}}
• Changing and Adding Dictionary elements
• Dictionaries are mutable. We can add new items or change the value of
existing items using an assignment operator.
• If the key is already present, then the existing value gets updated. In case the
key is not present, a new (key: value) pair is added to the dictionary.
• Example • Output
my_dict = {'name': 'Jack', {'name': 'Jack', 'age': 27}
'age': 26} {'name': 'Jack', 'age': 27,
'address': 'Downtown'}
my_dict['age'] = 27
print(my_dict)
my_dict['address'] = 'Downtown'
print(my_dict)
• Removing elements from Dictionary
• We can remove a particular item in a dictionary by using the pop() method.
This method removes an item with the provided key and returns the value.
• The popitem() method can be used to remove and return an
arbitrary (key, value) item pair from the dictionary. All the items can be
removed at once, using the clear() method.
• We can also use the del keyword to remove individual items or the entire
dictionary itself.
• Examples
• Output
• squares = {1: 1, 2: 4, 3: 9, 4:
16, 5: 25} 16
• {1: 1, 2: 4, 3: 9, 5: 25}
• print(squares.pop(4)) (5, 25)
• {1: 1, 2: 4, 3: 9}
• print(squares)
{}
•
Traceback (most recent call
• print(squares.popitem()) last):
•
File "<string>", line 30,
• print(squares) in <module>
•
print(squares)
• squares.clear()
NameError: name 'squares' is
•
not defined
• print(squares)
• Python Dictionary Comprehension
• Dictionary comprehension is an elegant and concise way to create a new dictionary from an
iterable in Python.
• Dictionary comprehension consists of an expression pair (key: value) followed by
a for statement inside curly braces {}.
• Here is an example to make a dictionary with each item being a pair of a number and its square.
• Example
• squares = {x: x*x for x in range(6)}
• print(squares)
This code is equivalent to
squares = {}
for x in range(6):
squares[x] = x*x
print(squares)
• Output
{0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
• Dictionary Membership Test
• We can test if a key is in a dictionary or not using the keyword in. Notice that the
membership test is only for the keys and not for the values.
• Example
• squares = {1: 1, 3: 9, 5: 25, 7: 49, 9: 81}
•
• print(1 in squares)
•
• print(2 not in squares)
•
• print(49 in squares)
• Output
True
True
False
• Iterating Through a Dictionary
• We can iterate through each key in a dictionary using a for loop.
• Example
• squares = {1: 1, 3: 9, 5: 25, 7: 49, 9: 81}
• for i in squares:
• print(squares[i])
• Output
1
9
25
49
81
• Python Dictionary Methods
Method Description
fromkeys(seq[, v]) Returns a new dictionary with keys from seq and value equal to v (defaults to None).
get(key[,d]) Returns the value of the key. If the key does not exist, returns d (defaults to None).
items() Return a new object of the dictionary's items in (key, value) format.
Removes the item with the key and returns its value or d if key is not found. If d is not provided and the key is not
pop(key[,d])
found, it raises KeyError.
popitem() Removes and returns an arbitrary item (key, value). Raises KeyError if the dictionary is empty.
Returns the corresponding value if the key is in the dictionary. If not, inserts the key with a value of d and returns d
setdefault(key[,d])
(defaults to None).
update([other]) Updates the dictionary with the key/value pairs from other, overwriting existing keys.
Function Description
all() Return True if all keys of the dictionary are True (or if the dictionary is empty).
any() Return True if any key of the dictionary is true. If the dictionary is empty, return False.
if (x % 2 == 0):
print("even")
else:
print("odd")
print(evenOdd.__doc__)
• Output
Function to check if the number is even or odd
• The return statement
• The function return statement is used to exit from a function and go back to the function
caller and return the specified value or data item to the caller.
• Syntax: return [expression_list]
• The return statement can consist of a variable, an expression, or a constant which is returned
to the end of the function execution. If none of the above is present with the return
statement a None object is returned.
• Example
def square_value(num):
"""This function returns the square
value of the entered number"""
return num**2
print(square_value(2))
print(square_value(-4))
• Output
4
16
• Creating a Function
• We can create a Python function using the def keyword.
• Calling a Function
• After creating a function we can call it by using the name of the function
followed by parenthesis containing parameters of that particular function.
• Example
def fun():
print("Welcome to Python World")
fun()
• Output
Welcome to Python World
• Arguments of a Function
• Arguments are the values passed inside the parenthesis of the function. A function can have any
number of arguments separated by a comma.
• Example: Python Function with arguments
• In this example, we will create a simple function to check whether the number passed as an
argument to the function is even or odd.
Example :
def evenOdd(x):
if (x % 2 == 0):
print("even")
else:
print("odd")
evenOdd(2)
evenOdd(3)
Output :
even
• Scope and Lifetime of variables
• Scope of a variable is the portion of a program where the variable is recognized. Parameters and
variables defined inside a function are not visible from outside the function. Hence, they have a local
scope.
• The lifetime of a variable is the period throughout which the variable exists in the memory. The
lifetime of variables inside a function is as long as the function executes.
• They are destroyed once we return from the function. Hence, a function does not remember the
value of a variable from its previous calls.
• Example
def my_func():
x = 10
print("Value inside function:",x)
x = 20
my_func()
print("Value outside function:",x)
• Output
Value inside function: 10
• Anonymous functions :
• In Python, an anonymous function means that a function is without a name.
As we already know the def keyword is used to define the normal functions
and the lambda keyword is used to create anonymous functions. Please
see this for details.
f2()
f1()
• Output
welcome
• Is Python Function Pass by Reference or pass by value?
• One important thing to note is, in Python every variable name is a reference.
When we pass a variable to a function, a new reference to the object is
created.
• Example
• def myFun(x):
x[0] = 20
lst = [10, 11, 12, 13, 14, 15]
myFun(lst)
print(lst)
• Output
[20, 11, 12, 13, 14, 15]
• Anonymous functions:
• In Python, an anonymous function means that a function is without a name. As we
already know the def keyword is used to define the normal functions and the
lambda keyword is used to create anonymous functions
• Python Lambda Functions are anonymous function means that the function is
without a name. As we already know that the def keyword is used to define a
normal function in Python. Similarly, the lambda keyword is used to define an
anonymous function in Python.
• Example :
def cube(x) :
return(x**3)
cube_var = lambda x : x**3
print('By Normal Funcion call :',cube(4))
print('By Lambda Function call :', cube_var(5))
• Output
By Normal Funcion call 64
By Lambda
Function call : 125
• Use of Lambda Function in python
In Python, we generally use it as an argument to a higher-order function (a
function that takes in other functions as arguments). Lambda functions are used
along with built-in functions like filter(), map() etc.
print(new_list)
• Output
[4, 6, 8, 12]
• Example use with map()
➢The map() function in Python takes in a function and a list.
➢The function is called with all the items in the list and a new list is returned
which contains items returned by that function for each item.
➢Here is an example use of map() function to double all the items in a list.
• Example
• # Program to double each item in a list using map()
•
• my_list = [1, 5, 4, 6, 8, 11, 3, 12]
•
• new_list = list(map(lambda x: x * 2 , my_list))
•
• print(new_list)
• Output
[2, 10, 8, 12, 16, 22, 6, 24]
• Recursion in Python
• The term Recursion can be defined as the process of defining something in
terms of itself. In simple words, it is a process in which a function calls itself
directly or indirectly.
• The following image shows the working of a recursive function
called recurse.
• Example
def factorial(x):
"""This is a recursive function
to find the factorial of an integer"""
if x == 1:
return 1
else:
return (x * factorial(x-1))
num = 3
print("The factorial of", num, "is", factorial(num))
• Output
The factorial of 3 is 6
• Advantages of Recursion
➢Recursive functions make the code look clean and elegant.
➢A complex task can be broken down into simpler sub-problems using
recursion.
➢Sequence generation is easier with recursion than using some nested
iteration.
• Disadvantages of Recursion
➢Sometimes the logic behind recursion is hard to follow through.
➢Recursive calls are expensive (inefficient) as they take up a lot of memory
and time.
➢Recursive functions are hard to debug.