(Lec Week 12)Intro to Python Part 2
(Lec Week 12)Intro to Python Part 2
Part 2
Dr Nisha Chaurasia
Python Part-2
What is Python?
Operators
Variables
Lists
If / Else
Loops
Unconditional Statement
Functions
Strings (Revisited)
Lists (Revisited)
Lists (Revisited)
List is an ordered sequence of items. Values in the list are called elements / items.
It can be written as a list of comma-separated items (values) between square
brackets[ ].
Items in the lists can be of different data types.
Lists can be understood as ordered, unchangeable (only elements can be
modified), heterogeneous (supports different data types) and contains duplicates.
Operations on list:
i. Indexing
ii. Slicing
iii. Concatenation
iv. Repetitions
Indexing/Slicing
Slicing Syntax:
list_varible(start:stop:step)
Accessing through loop
We can use the built-in list() function to convert other iterables (strings,
dictionaries, tuples, etc.) to a list.
Access List Elements
Each element in a list is associated with a number, known as an index.
The index of first item is 0, the index of second item is 1, and so on.
List slicing
Add Elements to a Python List
Use the append() method to add an element to the end of a Python list.
Use the insert() method to add an element at the specified index.
Use the extend() method to add elements to a list and add them at the end of the list.
Change List Items
The items of a list can be changed by assigning new values using the = operator.
The + operator can be used to concatenate two or more lists together
By using the * operator we can replicate our lists by the number of times we specify
Remove an Item From a List
Remove an item from a list using the remove() method
List Comprehension
List Comprehension is a concise and elegant way to create a list.
Syntax: [expression for item in list if condition == True]
List Methods
Nested List
The list can contain another list (sub-list), which in turn contains
another list and so on. This is termed a nested list.
Mutability in Lists
Mutability (can be changed) is
the ability for certain types of
data to be changed without
entirely recreating it.
An item can be changed in a
list by accessing it directly as
part of the assignment
statement.
Using the indexing operator
(square brackets[ ]) on the left
side of an assignment, one of
the list items can be updated
Aliasing (Copy) in Lists
Creating a copy of a list is
called aliasing.
Alaising refers to having
different names for same
list values.
When you create a copy Aliasing happens when multiple variables refer to
both the list will be having the same mutable object. Changes made to the
object through one alias are reflected in all other
same memory location. aliases, which can lead to unexpected behavior
Changes in one list will and bugs.