Python Part 2
Python Part 2
Part 2
List
Python Lists are just like the arrays, declared in other languages which is an
ordered collection of data. It is very flexible as the items in a list do not need to be
of the same type
Output
[1, 2, 3, ‘aa’, 2.3]
Arrays in Python
Python does not have built-in support for Arrays, but Python Lists can be used
instead.
Built in methods in list/array
Strings in Python
A sequence of characters enclosed in quotes.
print(text[0:5])
Dictionary
Python dictionary is like hash tables in any other language with the time
complexity of O(1).
It is used to store data values like a map, which, unlike other Data Types that hold
only a single value as an element, Dictionary holds the key:value pair.
● Python Tuple is a collection of Python objects much like a list but Tuples are
immutable in nature i.e. the elements in the tuple cannot be added or
removed once created.
● Just like a List, a Tuple can also contain elements of various types.
● In Python, tuples are created by placing a sequence of values separated by
‘comma’ with or without the use of parentheses for grouping of the data
sequence.
● Note: Tuples can also be created with a single element, but it is a bit tricky.
Having one element in the parentheses is not sufficient, there must be a
trailing ‘comma’ to make it a tuple.
TUPLE:
# Accessing element using indexing
# Creating a Tuple with print("First element of tuple")
# the use of Strings print(Tuple[0]) Output
Tuple with the use of String:
Tuple = ('a', 'br') ('a', 'b')
print("A" in Set)
# Accessing element using
# for loop
Function
def add(a, b):
return a + b
print(add(2, 3))
Lambda function
Anonymous, single-expression functions
square = lambda x: x ** 2
print(square(5))
Recursive FunctioN
def factorial(n):
if n == 1:
return 1
return n * factorial(n-1)
print(factorial(5))
def fib(n):
if n <= 1:
return n
print(fib(6))
Function
Function Scope & Lifetime
● Definition: Scope determines the visibility of a variable, and lifetime is how long it exists in
memory.
global_var = 10
def func():
local_var = 5
print(local_var)