Python Unit - 3( b ) List
Python Unit - 3( b ) List
INTRODUCTION TO PYTHON
PROGRAMMING
BCA – II YEAR
IV SEMESTER
By:-
Vinita Thanvi
Assistant Professor
Lucky Institute of Professional Studies
•Characteristics:
•Can store heterogeneous data types (integers, strings, floats, etc.).
•Supports indexing, slicing, and various operations.
•Example:
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)
list1 (List):
[ list1 ] ---> [ a, b, c]
| | |
10 "Hello" [1, 2, 3]
type()
• Lists are defined as objects with the data type 'list’:
<class 'list'>
• Example
list1 = ["apple", "banana", "cherry"]
print(type(list1))
# Inserting 5 at index 0
a.insert(0, 5)
print("After insert(0, 5):", a)
matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
• 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.
• 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.
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.
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]