0% found this document useful (0 votes)
2 views

Python Unit - 3( b ) List

The document is an introduction to Python programming focused on complex data types, specifically lists. It covers list creation, manipulation, slicing, and various methods for adding, updating, and removing elements. The content is aimed at BCA II year students and includes practical examples and explanations of list operations.

Uploaded by

vinitathanvi4clg
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Python Unit - 3( b ) List

The document is an introduction to Python programming focused on complex data types, specifically lists. It covers list creation, manipulation, slicing, and various methods for adding, updating, and removing elements. The content is aimed at BCA II year students and includes practical examples and explanations of list operations.

Uploaded by

vinitathanvi4clg
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 37

CSA 6007T

INTRODUCTION TO PYTHON
PROGRAMMING
BCA – II YEAR
IV SEMESTER

By:-
Vinita Thanvi
Assistant Professor
Lucky Institute of Professional Studies

By: Mrs. Vinita Thanvi Assistant Professor, IT Department, LIPS


By: Mrs. Vinita Thanvi Assistant Professor, IT Department, LIPS
Python Complex Data Types:
Using List and List Slicing, List Comprehension,
List Manipulation

By: Mrs. Vinita Thanvi Assistant Professor, IT Department, LIPS


Learning Objectives

By the end of this session, students will be able to:


1.Understand the concept of lists as a complex data type in Python.
2.Apply list slicing and indexing to extract and manipulate list elements.
3.Create and use list comprehensions for efficient list manipulation.
4.Manipulate lists using various list methods such as append(), remove(),
pop(), and more.

By: Mrs. Vinita Thanvi Assistant Professor, IT Department, LIPS


Introduction to Lists in Python
•Definition:
•A list in Python is an ordered collection of items that can be of any data
type, including other lists.
•Lists are mutable, meaning their contents can be changed.

•Characteristics:
•Can store heterogeneous data types (integers, strings, floats, etc.).
•Supports indexing, slicing, and various operations.

•Example:

my_list = [1, 2, 3.5, "Python", True]

By: Mrs. Vinita Thanvi Assistant Professor, IT Department, LIPS


List Declaration Syntax
•Creating a List:
•Using square brackets []:

my_list = [10, 20, 30]

List Items - Data Types


List items can be of any data type:
Example
• String, int and boolean data types:
list1 = ["apple", "banana", "cherry"]
list2 = [1, 5, 7, 9, 3]
list3 = [True, False, False]
• A list with mixed data types:
list4 = [1, "hello", 3.14, [1, 2, 3]]

By: Mrs. Vinita Thanvi Assistant Professor, IT Department, LIPS


The list list4 = [1, "hello", 3.14, [1, 2, 3]] is a Python list containing four elements
of different types. Here's an explanation of each element:
1.1: This is an integer. It's a whole number, which is one type of value that can be
stored in a list.

2."hello": This is a string. It's a sequence of characters enclosed in quotes, which


is another common data type that can be stored in lists.

3.3.14: This is a float. A float is a number that has a decimal point, representing
real numbers.

4.[1, 2, 3]: This is a nested list (a list inside another list). In this case, it contains
the integers 1, 2, and 3.

Python allows lists to store different types of data within a single list, which
makes it a very flexible data structure.
By: Mrs. Vinita Thanvi Assistant Professor, IT Department, LIPS
# Creating a Python list with different data types
a = [10, 20, “hello", 40, True]

print(a)

# Accessing elements using indexing


print(a[0]) # 10
print(a[1]) # 20
print(a[2]) # “hello"
print(a[3]) # 40
print(a[4]) # True

# Checking types of elements


print(type(a[2])) # str
print(type(a[4])) # bool

By: Mrs. Vinita Thanvi Assistant Professor, IT Department, LIPS


Note: Lists Store References, Not Values
• Each element in a list is not stored directly inside the list structure.
• Instead, the list stores references (pointers) to the actual objects in memory.
Concept
• When you create a list in Python, the list will contain references to objects, and these
objects could be numbers, strings, or even other lists or more complex data types.
• Example:
a = 10
b = "Hello“
c = [1, 2, 3]
list1 = [a, b, c]
• In this example:
a is an integer.
b is a string.
c is a list itself.
The list list1 contains references to the values of a, b, and c, not the actual values.

By: Mrs. Vinita Thanvi Assistant Professor, IT Department, LIPS


Memory:
[ a ] ---> 10 (integer object)
[ b ] ---> "Hello" (string object)
[ c ] ---> [1, 2, 3] (list object)

list1 (List):

[ list1 ] ---> [ a, b, c]
| | |
10 "Hello" [1, 2, 3]

By: Mrs. Vinita Thanvi Assistant Professor, IT Department, LIPS


Memory Location:
• a, b, and c are variables that store references to the actual objects (10,
"Hello", and [1, 2, 3]).
• The list list1 holds references to a, b, and c.

How References Work:


• The list list1 doesn't hold the actual objects (10, "Hello", and [1, 2, 3]).
Instead, it holds references (or memory address) to these objects.
• These references point to the locations in memory where the actual
values are stored.
Why is this important?
• If you modify an object that is referenced inside a list, the changes will
affect the object in memory.

By: Mrs. Vinita Thanvi Assistant Professor, IT Department, LIPS


• For example:
c[0] = 99
print(list1)
# Output: [10, 'Hello', [99, 2, 3]]
• This happens because c is a reference to the same list [1, 2, 3] that is inside
list1.
• Modifying c modifies the original list.
• If you assign one list to another, both lists will reference the same objects.
• For example:
list2 = list1
list2[0] = 20
print(list1)
# Output: [20, 'Hello', [99, 2, 3]]
• Here, modifying list2 affects list1 because both list1 and list2 refer to the
same objects in memory.
By: Mrs. Vinita Thanvi Assistant Professor, IT Department, LIPS
List Length
• To determine how many items a list has, use the len() function:
• Example - Print the number of items in the list
• list1 = ["apple", "banana", "cherry"]
• print(len(list1))

type()
• Lists are defined as objects with the data type 'list’:
<class 'list'>
• Example
list1 = ["apple", "banana", "cherry"]
print(type(list1))

By: Mrs. Vinita Thanvi Assistant Professor, IT Department, LIPS


The list() Constructor
• It is also possible to use the list() constructor when creating a
new list.
• Example
list1 = list(("apple", "banana", "cherry"))
# note the double round-brackets
print(list1)

By: Mrs. Vinita Thanvi Assistant Professor, IT Department, LIPS


• The code list1 = list(("apple", "banana", "cherry")) uses double round brackets
for creating a list from a tuple.
• ("apple", "banana", "cherry"): This is a tuple, which is an immutable sequence
type in Python. Tuples are created by enclosing elements in parentheses ().
Tuples can store multiple items, like lists, but unlike lists, they cannot be
changed (i.e., they are immutable).
• list(): The list() function is used to convert an iterable (like a tuple, string, or
other sequence types) into a list. So when you do:
list1 = list(("apple", "banana", "cherry"))
• The double round brackets have a specific purpose:
• The first pair () is for creating a tuple: ("apple", "banana", "cherry").
• The second pair () is for calling the list() function, which converts the tuple
into a list.
• The result is a list list1 that looks like ['apple', 'banana', 'cherry’]
Why the double round brackets?
• The first () is just to define the tuple.
• The second () is to pass the tuple as an argument to the list() function.
By: Mrs. Vinita Thanvi Assistant Professor, IT Department, LIPS
Creating List with Repeated Elements
• We can create a list with repeated elements using the
multiplication operator.
• # Create a list [2, 2, 2, 2, 2]
a = [2] * 5
• # Create a list [0, 0, 0, 0, 0, 0, 0]
b = [0] * 7
print(a)
print(b)

By: Mrs. Vinita Thanvi Assistant Professor, IT Department, LIPS


Accessing List Elements
• Elements in a list can be accessed using indexing.
• Python indexes start at 0, so a[0] will access the first element, while
negative indexing allows us to access elements from the end of the
list. Like index -1 represents the last elements of list.
• Example
a = [10, 20, 30, 40, 50]

# Access first element


print(a[0])

# Access last element


print(a[-1])

By: Mrs. Vinita Thanvi Assistant Professor, IT Department, LIPS


Adding Elements into List
We can add elements to a list using the following methods:

• append(): Adds an element at the end of the list.


• extend(): Adds multiple elements to the end of the list.
• insert(): Adds an element at a specific position.

By: Mrs. Vinita Thanvi Assistant Professor, IT Department, LIPS


# Initialize an empty list
a = []

# Adding 10 to end of list


a.append(10)
print("After append(10):", a)

# Inserting 5 at index 0
a.insert(0, 5)
print("After insert(0, 5):", a)

# Adding multiple elements [15, 20, 25] at the


end
a.extend([15, 20, 25])
print("After extend([15, 20, 25]):", a)

By: Mrs. Vinita Thanvi Assistant Professor, IT Department, LIPS


Updating Elements into List
We can change the value of an element by accessing it using its index.

a = [10, 20, 30, 40, 50]


# Change the second element
a[1] = 25
print(a)

By: Mrs. Vinita Thanvi Assistant Professor, IT Department, LIPS


Removing Elements from List
We can remove elements from a list using:

• remove(): Removes the first occurrence of an element.


• pop(): Removes the element at a specific index or the last
element if no index is specified.
• del statement: Deletes an element at a specified index.

By: Mrs. Vinita Thanvi Assistant Professor, IT Department, LIPS


a = [10, 20, 30, 40, 50]

# Removes the first occurrence of 30


a.remove(30)
print("After remove(30):", a)

# Removes the element at index 1 (20)


popped_val = a.pop(1)
print("Popped element:", popped_val)
print("After pop(1):", a)

# Deletes the first element (10)


del a[0]
print("After del a[0]:", a)

By: Mrs. Vinita Thanvi Assistant Professor, IT Department, LIPS


Iterating Over Lists
• We can iterate the Lists easily by using a for loop or other iteration methods.
• Iterating over lists is useful when we want to do some operation on each
item or access specific items based on certain conditions.
• Using for Loop

a = ['apple', 'banana', 'cherry']


# Iterating over the list
for item in a:
print(item)

By: Mrs. Vinita Thanvi Assistant Professor, IT Department, LIPS


Nested Lists in Python
• A nested list is a list within another list, which is useful for
representing matrices or tables.
• We can access nested elements by chaining indexes.

matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]

# Access element at row 2, column 3


print(matrix[1][2])

By: Mrs. Vinita Thanvi Assistant Professor, IT Department, LIPS


List slicing
• List slicing in Python is a powerful feature that allows you to extract a subset
or portion of a list.
• It uses the slice notation to create a new list that contains elements from the
original list, without modifying the original list.
• Syntax of List Slicing:
list[start:end:step]
start: The index at which the slice starts (inclusive). If not provided, it
defaults to 0 (start of the list).
end: The index at which the slice ends (exclusive). If not provided, it defaults
to the length of the list (i.e., the slice will go until the end).
step: The step size, which specifies how much to increment between indices.
If not provided, it defaults to 1.

By: Mrs. Vinita Thanvi Assistant Professor, IT Department, LIPS


Basic Slicing:

my_list = [10, 20, 30, 40, 50, 60, 70]


#To extract a subset of the list from index 1 to 4:
print(my_list[1:4])
# Output: [20, 30, 40]
This includes elements from index 1 to index 3, excluding the
element at index 4.

By: Mrs. Vinita Thanvi Assistant Professor, IT Department, LIPS


• Omitting Start or End Index:

• No start (defaults to 0):


my_list = [10, 20, 30, 40, 50, 60, 70]
print(my_list[:4])
# [10, 20, 30, 40]
• This returns elements from the start (index 0) up to index 3.
• No end (defaults to the length of the list):
print(my_list[3:])
# [40, 50, 60, 70]
• This returns elements from index 3 to the end of the list.

By: Mrs. Vinita Thanvi Assistant Professor, IT Department, LIPS


Step Argument:
• The step argument defines how we move between elements in the
slice.
• With step 2:
my_list = [10, 20, 30, 40, 50, 60, 70]
print(my_list[::2]) # [10, 30, 50, 70]
This selects every second element starting from the beginning.
• Negative step (reversing the list):
my_list = [10, 20, 30, 40, 50, 60, 70]
print(my_list[::-1]) # [70, 60, 50, 40, 30, 20, 10]
This returns the list in reverse order, starting from the last element
and going backward.

By: Mrs. Vinita Thanvi Assistant Professor, IT Department, LIPS


Negative Indices:

• Python allows the use of negative indices, which count from the
end of the list.
• Example with negative start and end:
my_list = [10, 20, 30, 40, 50, 60, 70]
print(my_list[-3:-1]) # [50, 60]
This slice starts at index -3 (which corresponds to 50) and ends
at index -1 (which corresponds to 60), but does not include -1.

By: Mrs. Vinita Thanvi Assistant Professor, IT Department, LIPS


Combining Start, End, and Step:

• You can combine all three parameters (start, end, and step) to get
more specific slices.
• Extract elements from index 1 to 5, skipping every 2nd element:
my_list = [10, 20, 30, 40, 50, 60, 70]
print(my_list[1:5:2]) # [20, 40]
This slice starts at index 1 (which is 20), goes up to index 4
(which is 50), and takes every second element.

By: Mrs. Vinita Thanvi Assistant Professor, IT Department, LIPS


Summary of List Slicing:

• Basic slicing: list[start:end]


• Omit start: list[:end] (defaults to start of the list)
• Omit end: list[start:] (defaults to the end of the list)
• Negative indices: list[-n:] starts from the end of the list.
• Step slicing: list[start:end:step] allows you to skip elements or
reverse the list.

Key Points:

• List slicing creates a new list that is a subset of the original list.
• The start index is inclusive, and the end index is exclusive.
• The step defines how elements are selected from the original list.
By: Mrs. Vinita Thanvi Assistant Professor, IT Department, LIPS
Practical Example of List Manipulation
•Task: Filter a list to find all numbers greater than 10 and square them.

numbers = [5, 15, 8, 22, 3, 11]


result = [] # Create an empty list to store the results

# Iterate over each number in the 'numbers' list


for x in numbers:
if x > 10: # Check if the number is greater than 10
result.append(x**2) # If True, square the number and append to 'result'
#result = [x**2 for x in numbers if x > 10] shortcut method
print(result) # Output: [225, 484, 121]

By: Mrs. Vinita Thanvi Assistant Professor, IT Department, LIPS


Summary:

•Lists are ordered, mutable collections in Python that can store


heterogeneous data types.
•You can slice and index lists to access individual elements or
sublists.
•Common list methods include append(), insert(), remove(),
pop(), and sort().
•List comprehension provides a concise syntax for creating and
manipulating lists.

By: Mrs. Vinita Thanvi Assistant Professor, IT Department, LIPS


Quiz (Assessment)

1.What will be the output of the following code?

my_list = [1, 2, 3, 4, 5]
print(my_list[1:4])
a) [1, 2, 3]
b) [2, 3, 4]
c) [3, 4, 5]
d) [1, 2, 3, 4]

2.Which list method is used to add an element at the end of a


list?
a) append()
b) insert()
c) pop()
d) remove()
By: Mrs. Vinita Thanvi Assistant Professor, IT Department, LIPS
3.What will be the output of this list comprehension?

squares = [x**2 for x in range(3, 7)]


print(squares)
a) [9, 16, 25, 36]
b) [3, 6, 9, 12]
c) [1, 4, 9, 16]
d) [3, 5, 7, 9]

By: Mrs. Vinita Thanvi Assistant Professor, IT Department, LIPS


Assignments

1.Write a Python program that takes a list of numbers and returns a


new list that contains only the even numbers squared.

2.Create a function that accepts a list and removes all occurrences of a


given element.

3.Using list comprehension, create a program that takes a string and


returns a list of words that are longer than 4 characters.

By: Mrs. Vinita Thanvi Assistant Professor, IT Department, LIPS


Thank You
By: Mrs. Vinita Thanvi Assistant Professor, IT Department, LIPS

You might also like