Download as pdf or txt
Download as pdf or txt
You are on page 1of 19

data structures reviewer | lim_shin

PYTHON LISTS Using list() constructor: In general, the


constructor of a class has its class name. Similarly,
Python list – is an ordered sequence of items.
Create a list by passing the comma-separated
values inside the list().
PROPERTIES OF A LIST
Using square bracket ([]): In this method, we can
1. MUTABLE: The elements of the list can be
create a list simply by enclosing the items inside the
modified. We can add or remove items to
square brackets.
the list after it has been created.

2. ORDERED: The items in the lists are


ordered. Each item has a unique index
value. The new items will be added to the
end of the list.

3. HETEROGENOUS: The list can contain


different kinds of elements i.e; they can
contain elements of string, integer, boolean,
or any type.

4. DUPLICATES: The list can contain


duplicates i.e., lists can have two items with
the same values.

WHY USE A LIST?

• The list data structure is very flexible It has


many unique inbuilt functionalities like pop(),
append(), etc which makes it easier, where the
data keeps changing.

• List can contain duplicate elements i.e two or


more items can have the same values.

• Lists are Heterogeneous i.e, different kinds of


objects/elements can be added

• As Lists are mutable it is used in applications


where the values of the items change LENGTH OF A LIST
frequently.
In order to find the number of items present in a list,
we can use len() function
CREATING A PYTHON LIST

The list can be created using either the list


constructor or using square brackets [].

Page | 1
data structures reviewer | lim_shin

As seen in the above example we accessed the


ACCESSING ITEMS OF A LIST second element in the list by passing the index
value as 1. Similarly, we passed index 4 to access
• Using indexing, we can access any item from a
the 5th element in the list.
list using its index number
NEGATIVE INDEXING
• Using slicing, we can access a range of items
from a list The elements in the list can be accessed from right
to left by using negative indexing. The negative
value starts from -1 to -length of the list. It indicates
INDEXING that the list is indexed from the reverse/backward.
Lists are ordered collections with unique indexes
for each item

To access the elements in the list from left to


right, the index value starts from zero to (length
of the list-1) can be used. For example, if we want
to access the 3rd element we need to use 2 since
the index value starts from 0.

NOTE:

• As Lists are ordered sequences of items, the


index values start from 0 to the Lists length.
• Whenever we try to access an item with an
As seen in the above example to access the 4th
index more than the Lists length, it will throw the
element from the last (right to left) we pass ‘-4’ in
'Index Error'.
the index value.
• Similarly, the index values are always an
integer. If we give any other type, then it will LIST SLICING
throw Type Error.
Slicing a list implies, accessing a range of elements
in a list. For example, if we want to get the elements
in the position from 3 to 7, we can use the slicing
method. We can even modify the values in a range
by using this slicing technique.

’ Below is the syntax for list slicing:

Page | 2
data structures reviewer | lim_shin

• The start_index denotes the index position


from where the slicing should begin and the
end_index parameter denotes the index
positions till which the slicing should be done.
• The step allows you to take each nth-element
within a start_index:end_index range.

ITERATE ALONG WITH AN INDEX NUMBER

The index value starts from 0 to (length of the list-


Let us see few more examples of slicing a list such 1). Hence using the function range() is ideal for this
as: scenario.

• Extract a portion of the list The range function returns a sequence of numbers.
• Reverse a list By default, it returns starting from 0 to the specified
number (increments by 1). The starting and ending
• Slicing with a step
values can be passed according to our needs.
• Slice without specifying start or end position

ADDING ELEMENTS TO THE LIST

We can add a new element/list of elements to the


list using the list methods such as append(),
insert(), and extend()

ITERATING A LIST

The objects in the list can be iterated over one by


one, by using a for a loop. APPEND ITEM AT THE END OF THE LIST

The append() method will accept only one


parameter and add it at the end of the list.

Let’s see the example to add the element ‘Emma’ at


the end of the list.

Page | 3
data structures reviewer | lim_shin

USING extend()

The extend method will accept the list of elements


and add them at the end of the list. We can even
add another list by using this method.

Let’s add three items at the end of the list.

As seen in the above example we have three


integer values at once. All the values get added in
the order they were passed and it gets appended at
ADD ITEM AT THE SPECIFIED POSITION IN THE the end of the list.
LIST
MODIFY THE ITEMS OF A LIST
Use the insert() method to add the object/item
The list is a mutable sequence of iterable objects. It
at the specified position in the list. The insert
means we can modify the items of a list. Use the
method accepts two parameters position and
index number and assignment operator (=) to
object.
assign a new value to an item.

Let’s see how to perform the following two


modification scenarios
It will insert the object in the specified index. Let
• Modify the individual item.
us see this with an example.
• Modify the range of items

As seen in the above example item 25 is added at


the index position 2.

Page | 4
data structures reviewer | lim_shin

MODIFY ALL ITEMS

Use for loop to iterate and modify all items at once.


Let’s see how to modify each item of a list.

REMOVE ITEM PRESENT AT GIVEN INDEX

Use the pop() method to remove the item at the


given index. The pop() method removes and
returns the item present at the given index.

Note: It will remove the last time from the list if the
index number is not passed.

REMOVING ELEMENTS FROM A LIST

remove(item) – to remove the first occurrence of


the item from the list

pop(index) – removes and returns the item at the


given index from the list

clear() – to remove all items from the list. The


output will be an empty list

del list_name – delete the entire list

REMOVE SPECIFIC ITEM

Use the remove() method to remove the first


occurrence of the item from the list.

Note: It Throws a keyerror if an item not present


in the original list.

Page | 5
data structures reviewer | lim_shin

REMOVE THE RANGE OF ITEMS FINDING AN ELEMENT IN THE LIST

Use del keyword along with list slicing to remove Use the index() function to find an item in a list.
the range of items
The index() function will accept the value of the
element as a parameter and returns the first
occurrence of the element or returns ValueError if
the element does not exist.

CONCATENATION OF TWO LISTS

The concatenation of two lists means merging of


two lists. There are two ways to do that.

• Using the + operator.


REMOVE ALL ITEMS • Using the extend() method. The extend()
method appends the new list’s items at the end
Use the list’ clear() method to remove all items of the calling list.
from the list. The clear() method truncates the
list.

Page | 6
data structures reviewer | lim_shin

COPYING A LIST Using the copy() method

There are two ways by which a copy of a list can be The copy method can be used to create a copy of a
created. Let us see each one with an example. list. This will create a new list and any changes
made in the original list will not reflect in the new
Using assignment operator (=)
list. This is shallow copying.
This is a straightforward way of creating a copy. In
this method, the new list will be a deep copy. The
changes that we make in the original list will be
reflected in the new list.

This is called deep copying.

As seen in the above example a copy of the list has


been created. The changes made to the original list
are not reflected in the copy.

LIST OPERATIONS

As seen in the above example a copy of the list has We can perform some operations over the list by
been created. The changes made to the original list using certain functions like sort(), reverse(),
are reflected in the copied list as well. clear() etc.

Note: When you set list1 = list2, you are Sort List using sort()
making them refer to the same list object, so
The sort function sorts the elements in the list in
when you modify one of them, all references
ascending order.
associated with that object reflect the current state
of the object. So don’t use the assignment operator
to copy the dictionary instead use the copy()
method.
OUTPUT:

Page | 7
data structures reviewer | lim_shin

Reverse a List using reverse() We can even create a list when the input is a
continuous range of numbers.
The reverse function is used to reverse the
elements in the list.

OUTPUT:

OUTPUT:

As seen in the above example we have created a


list of squares of only even numbers in a range. The
LIST COMPREHENSION output is again a list so the items will be ordered.
List comprehension is a simpler method to create a SUMMARY OF LIST OPERATIONS
list from an existing list. It is generally a list of
iterables generated with an option to include only For the following examples, we assume that l1 and
the items which satisfy a condition. l2 are lists, x, i, j, k, n are integers.

outputList = {expression(variable) for variable in l1 = [10, 20, 30, 40, 50] and l2 = [60,
inputList [if variable condition1][if variable 70, 80, 60]
condition2]

expression: Optional. expression to compute the


members of the output List which satisfies the
optional conditions

variable: Required. a variable that represents the


members of the input List.

inputList: Required. Represents the input set.

condition1, condition2 etc; : Optional. Filter


conditions for the members of the output List.

OUTPUT:

As seen in the above example we have created a


new list from an existing input list in a single
statement. The new list now contains only the
squares of the even numbers present in the input
list.

Page | 8
data structures reviewer | lim_shin

PYTHON OBJECT-ORIENTED PROGRAMMING


(OOP)

• Object-oriented programming (OOP) is a


programming paradigm based on the concept
of "objects".
• The object contains both data and code: Data in
the form of properties (often known as
attributes), and code, in the form of methods
(actions object can perform).
• An object-oriented paradigm is to design the
program using classes and objects.
• Python programming language supports
different programming approaches like
functional programming, modular programming.
• One of the popular approaches is object-
oriented programming (OOP) to solve a
programming problem is by creating objects

An object has the following two characteristics:

• Attribute
• Behavior

For example, A Car is an object, as it has the


following properties:

• name, price, color as attributes


• breaking, acceleration as behavior

One important aspect of OOP in Python is to create


reusable code using the concept of inheritance.
This concept is also known as DRY (Don't Repeat
Yourself)

Page | 9
data structures reviewer | lim_shin

CLASS AND OBJECTS constructor ( the __init__() method of a


class).
• In Python, everything is an object.
2. Class Variables: A class variable is a
• A class is a blueprint for the object.
variable that is declared inside of class, but
• To create an object we require a model or
outside of any instance method or
plan or blueprint which is nothing but class.
__init()__ method.
For example, you are creating a vehicle according
Inside a Class, we can define the following three
to the Vehicle blueprint (template). The plan
types of methods.
contains all dimensions and structure. Based on
these descriptions, we can construct a car, truck, 1. Instance method: Used to access or modify
bus, or any vehicle. Here, a car, truck, bus are the object attributes. If we use instance
objects of Vehicle class variables inside a method, such methods
are called instance methods.
• A class contains the properties (attribute)
2. Class method: Used to access or modify
and action (behavior) of the object.
the class state. In method implementation, if
• Properties represent variables, and the
we use only class variables, then such type
methods represent actions.
of methods we should declare as a class
• Hence class includes both variables and method.
methods. 3. Static method: It is a general utility method
that performs a task in isolation. Inside this
method, we don’t use instance or class
variable because this static method doesn’t
have access to the class attributes.

CREATING CLASS AND OBJECTS

In Python, Use the keyword class to define a


Class. In the class definition, the first string is
docstring which, is a brief description of the class.

The docstring is not mandatory but recommended


to use. We can get docstring using __doc__
• Object is an instance of a class. attribute. Use the following syntax to create a
class.
The physical existence of a class is nothing but an
object. In other words, the object is an entity that
has a state and behavior. It may be any real-world
object like the mouse, keyboard, laptop, etc.

CLASS ATTRIBUTES AND METHODS


Documentation string: represent a description of
When we design a class, we use instance variables the class. It is optional.
and class variables.
class_suite: class suite contains class attributes
In Class, attributes can be defined into two parts: and methods
1. Instance variables: The instance variables
are attributes attached to an instance of a
class. We define instance variables in the

Page | 10
data structures reviewer | lim_shin

OOP EXAMPLE: CREATING CLASS AND OBJECT CONSTRUCTORS IN PYTHON


IN PYTHON
• A constructor is a special method used to
create and initialize an object of a class. This
method is defined in the class.
• The constructor is executed automatically at the
time of object creation.
• The primary use of a constructor is to declare
and initialize data member/ instance variables of
a class. The constructor contains a collection of
statements (i.e., instructions) that executes at
the time of object creation to initialize the
attributes of an object.

For example, when we execute obj = Sample(),


Python gets to know that obj is an object of class
Sample and calls the constructor of that class to
create an object.

OUTPUT: NOTE: In Python, internally, the __new__ is the


method that creates the object, and __del__
method is called to destroy the object when the
reference count for that object becomes zero.
• In the above example, we created a Class In Python, Object creation is divided into two parts
with the name Employee. in Object Creation and Object initialization
• Next, we defined two attributes name and
salary. • Internally, the __new__ is the method that
• Next, in the __init__() method, we creates the object
initialized the value of attributes. This • And, using the __init__() method we can
method is called as soon as the object is implement constructor to initialize the object
created. The init method initializes the Syntax of a constructor
object.
• Finally, from the Employee class, we created
two objects, Emma and Harry.
• Using the object, we can access and modify
its attributes. • def: The keyword is used to define function.
• __init__() Method: It is a reserved method.
This method gets called as soon as an object of
a class is instantiated.
• self: The first argument self refers to the
current object. It binds the instance to the
__init__() method. It’s usually named self to
follow the naming convention.

NOTE: The __init__() method arguments are


optional. We can define a constructor with any
number of arguments.

Page | 11
data structures reviewer | lim_shin

EXAMPLE: CREATE A CONSTRUCTOR IN NOTE:


PYTHON
• For every object, the constructor will be
In this example, we’ll create a Class Student with an executed only once. For example, if we create
instance variable student name. we’ll see how to four objects, the constructor is called four times.
use a constructor to initialize the student name at • In Python, every class has a constructor, but it’s
the time of object creation. not required to define it explicitly. Defining
constructors in class is optional.
• Python will provide a default constructor if no
constructor is defined.

TYPES OF CONSTRUCTORS

In Python, we have the following three types of


constructors.

1. Default Constructor
2. Non-parametrized constructor
3. Parameterized constructor

OUTPUT:

In the above example, an object s1 is created using


the constructor

While creating a Student object name is passed as


an argument to the __init__() method to initialize
the object.
DEFAULT CONSTRUCTOR
Similarly, various objects of the Student class can
▪ Python will provide a default constructor if no
be created by passing different names as
constructor is defined.
arguments.
▪ Python adds a default constructor when we do
not include the constructor in the class or forget
to declare it.
▪ It does not perform any task but initializes the
objects. It is an empty constructor without a
body.

If you do not implement any constructor in your


class or forget to declare it, the Python inserts a
default constructor into your code on your behalf.
This constructor is known as the default
constructor.

Page | 12
data structures reviewer | lim_shin

NOTE:

• The default constructor is not present in the


source py file. It is inserted into the code during
compilation if not exists. See the below image.
• If you implement your constructor, then the
default constructor will not be added.

OUTPUT:

As you can see in the example, we do not send any


argument to a constructor while creating an object.

PARAMETERIZED CONSTRUCTOR

▪ A constructor with defined parameters or


arguments is called a parameterized
constructor.
▪ We can pass different values to each object at
As you can see in the example, we do not have a the time of creation using a parameterized
constructor, but we can still create an object for the constructor.
class because Python added the default constructor ▪ The first parameter to constructor is self that is
during a program compilation. a reference to the being constructed, and the
rest of the arguments are provided by the
programmer.
NON-PARAMETRIZED CONSTRUCTOR ▪ A parameterized constructor can have any
▪ A constructor without any arguments is called a number of arguments.
non-parameterized constructor. ▪ For example, consider a company that contains
▪ This type of constructor is used to initialize each thousands of employees. In this case, while
object with default values. creating each employee object, we need to
▪ This constructor doesn’t accept the pass a different name, age, and salary. In such
arguments during object creation. Instead, it cases, use the parameterized constructor.
initializes every object with the same set of
values.

Page | 13
data structures reviewer | lim_shin

self Keyword in Python

• As you all know, the class contains instance


variables and methods. Whenever we define
instance methods for a class, we use self as the
first parameter.
• Using self, we can access the instance
variable and instance method of the object.
• The first argument self refers to the current
object.
• Whenever we call an instance method through
an object, the Python compiler implicitly passes
object reference as the first argument
commonly known as self.
OUTPUT:
• It is not mandatory to name the first parameter
as a self. We can give any name whatever we
like, but it has to be the first parameter of an
instance method.
CONSTRUCTOR WITH DEFAULT VALUES

Python allows us to define a constructor with


default values. The default value will be used if we
do not pass arguments to the constructor at the
time of object creation.

OUTPUT:
OUTPUT:

As you can see, we didn’t pass the age and


classroom value at the time of object creation, so
default values are used.

Page | 14
data structures reviewer | lim_shin

CONSTRUCTOR OVERLOADING CONSTRUCTOR CHAINING

• Constructor overloading is a concept of having • Constructors are used for instantiating an


more than one constructor with a different object. The task of the constructor is to assign
parameters list in such a way so that each value to data members when an object of the
constructor can perform different tasks. class is created.
• For example, we can create a three constructor • Constructor chaining is the process of calling
which accepts a different set of parameter one constructor from another constructor.
• Python does not support constructor Constructor chaining is useful when you want to
overloading. invoke multiple constructors, one after another,
• If we define multiple constructors then, the by initializing only one instance.
interpreter will considers only the last • In Python, constructor chaining is convenient
constructor and throws an error if the sequence when we are dealing with inheritance. When an
of the arguments doesn’t match as per the last instance of a child class is initialized, the
constructor. constructors of all the parent classes are first
invoked and then, in the end, the constructor of
the child class is invoked.
• Using the super() method we can invoke the
parent class constructor from a child class.

OUTPUT:

• As you can see in the above example, we


defined multiple constructors with different
arguments. OUTPUT:
• At the time of object creation, the interpreter
executed the second constructor because
Python always considers the last constructor.
• Internally, the object of the class will always call
the last constructor, even if the class has
multiple constructors.
• In the example when we called a constructor
only with one argument, we got a type error.

Page | 15
data structures reviewer | lim_shin

COUNTING THE NUMBER OF OBJECTS OF A PYTHON DATA STRUCTURE EXERCISES FOR


CLASS BEGINNERS

• The constructor executes when we create the Exercise 1: Create a list by picking an odd-index
object of the class. For every object, the items from the first list and even index items from
constructor is called only once. the second
• So, for counting the number of objects of a
Given two lists, l1 and l2, write a program to create
class, we can add a counter in the constructor,
a third list l3 by picking an odd-index element from
which increments by one after each object
the list l1 and even index elements from the list l2.
creation.
SOLUTION:

To access a range of items in a list, use the slicing


operator :. With this operator, you can specify
where to start the slicing, end, and specify the step.

For example, the expression list1[ start :


stop : step] returns the portion of the list from
index start to index stop, at a step size step.

➢ for 1st list: Start from the 1st index with step
OUTPUT: value 2 so it will pick elements present at
index 1, 3, 5, and so on
➢ for 2nd list: Start from the 0th index with
step value 2 so it will pick elements present
CONSTRUCTOR RETURN VALUE at index 0, 2, 4, and so on
• In Python, the constructor does not return any
value. Therefore, while declaring a constructor,
we don’t have anything like return type.
• Instead, a constructor is implicitly called at the
time of object instantiation. Thus, it has the sole
purpose of initializing the instance variables.
• The __init__() is required to return None. We
can not return something else. If we try to return
a non-None value from the __init__()
method, it will raise TypeError.

OUTPUT:

OUTPUT:

Page | 16
data structures reviewer | lim_shin

Exercise 2: Remove and add item in a list

Write a program to remove the item present at


index 4 and add it to the 2nd position and at the
end of the list.

SOLUTION:

➢ pop(index): Removes and returns the item at


the given index from the list.
➢ insert(index, item): Add the item at the
specified position(index) in the list
➢ append(item): Add item at the end of the list.

OUTPUT:

OUTPUT:

Exercise 4: Count the occurrence of each element


from a list
Exercise 3: Slice list into 3 equal chunks and
Write a program to iterate a given list and count the
reverse each chunk
occurrence of each element and create a dictionary
SOLUTION: to show the count of each element.

➢ Get the length of a list using a len() function


➢ Divide the length by 3 to get the chunk size
➢ Run loop three times
➢ In each iteration, get a chunk using a
slice(start, end, step) function and
reverse it using the reversed() function
➢ In each iteration, start and end value will
change

OUTPUT:

Page | 17
data structures reviewer | lim_shin

Exercise 5: Create a Python set such that it shows


the element from both lists in a pair

SOLUTION:

OUTPUT:

PYTHON LIST QUIZ

Page | 18
data structures reviewer | lim_shin

Page | 19

You might also like