100218- Python
Programming
Module 4: Lists
➢ Creating Lists:
• List: In Python, lists are ordered, mutable collections of items. They are a
fundamental data structure and can hold items of different data types
within the same list.
• Creating a List:
1. Creating an Empty List: An empty list can be created by assigning an
empty pair of square brackets [] to a variable.
my_empty_list = []
2. Creating a List with Initial Elements: To create a list with elements,
enclose the elements within square brackets [] and separate them with
commas.
# List of integers
numbers = [1, 2, 3, 4, 5]
# List of strings
fruits = ["apple", "banana", "cherry"]
# List with mixed data types
mixed_list = [10, "hello", True, 3.14]
➢ Creating Lists:
3. Creating a List using the list() constructor: The list() constructor can
be used to convert other iterable objects (like tuples, strings, or
other lists) into a list.
# From a tuple
my_tuple = (1, 2, 3)
list_from_tuple = list(my_tuple)
# From a string (creates a list of characters)
my_string = "Python"
list_from_string = list(my_string)
4. Creating a List using List Comprehension: List comprehension
provides a concise way to create lists based on existing iterables. It
is often more efficient than using a for loop with append().
# Create a list of squares of numbers from 0 to 4
squares = [x**2 for x in range(5)] # Output: [0, 1, 4, 9, 16]
# Create a list of even numbers from a range
even_numbers = [num for num in range(10) if num % 2 == 0] # Output: [0, 2, 4, 6, 8]
➢ Basic List Operations:
• List Operations: Python lists are versatile, ordered, and mutable
collections of items. Basic operations include:
1. Creating a List: Lists are created by enclosing comma-separated items
within square brackets [].
my_list = [1, 2, "hello", True]
empty_list = []
2. Accessing Elements: Elements are accessed using their index, starting
from 0 for the first element.
my_list = ["apple", "banana", "cherry"]
first_item = my_list[0] # "apple"
last_item = my_list[-1] # "cherry" (negative indexing accesses from the end)
3. Modifying Elements: Elements can be changed by assigning a new value
to a specific index.
my_list = [10, 20, 30]
my_list[1] = 25 # my_list is now [10, 25, 30]
➢ Basic List Operations:
4. Adding Elements:
append(item): Adds an item to the end of the list.
insert(index, item): Inserts an item at a specified index.
extend(iterable): Adds all items from an iterable (e.g., another list) to the end of the current list.
my_list = [1, 2]
my_list.append(3) # [1, 2, 3]
my_list.insert(1, 1.5) # [1, 1.5, 2, 3]
another_list = [4, 5]
my_list.extend(another_list) # [1, 1.5, 2, 3, 4, 5]
5. Removing Elements:
remove(value): Removes the first occurrence of a specified value.
pop(index): Removes and returns the element at a given index (defaults to the last element if no index is provided).
del list[index]: Deletes the item at a specific index.
clear(): Removes all elements from the list.
my_list = ["a", "b", "c", "b"]
my_list.remove("b") # ["a", "c", "b"]
popped_item = my_list.pop(0) # popped_item is "a", my_list is ["c", "b"]
del my_list[0] # my_list is ["b"]
my_list.clear() # my_list is []
6. Slicing Lists:
Extracts a subset of elements using [start:end:step].
numbers = [1, 2, 3, 4, 5]
subset = numbers[1:4] # [2, 3, 4]
copy_list = numbers[:] # Creates a shallow copy
➢ Basic List Operations:
7. List Concatenation and Replication:
+ operator: Concatenates two or more lists into a new list.
* operator: Replicates a list multiple times.
list1 = [1, 2]
list2 = [3, 4]
combined_list = list1 + list2 # [1, 2, 3, 4]
repeated_list = list1 * 3 # [1, 2, 1, 2, 1, 2]
8. Other Useful Operations:
• len(list): Returns the number of elements in the list.
• min(list), max(list), sum(list): Return the minimum, maximum, and
sum of elements in a list of numbers.
• [Link](): Sorts the list in-place.
• sorted(list): Returns a new sorted list without modifying the
original.
• item in list: Checks for membership.
➢ Indexing and Slicing in Lists:
• Indexing and slicing are fundamental operations in Python for
accessing elements or sub-sequences within lists.
• Indexing: Indexing allows access to individual elements within a
list using their position or index.
1. Positive Indexing: Elements are indexed starting from 0 for the first
element, 1 for the second, and so on.
my_list = ['apple', 'banana', 'cherry']
print(my_list[0]) # Output: 'apple'
print(my_list[2]) # Output: 'cherry'
2. Negative Indexing: Elements can also be accessed from the end of
the list using negative indices. -1 refers to the last element, -2 to the
second to last, and so on.
my_list = ['apple', 'banana', 'cherry']
print(my_list[-1]) # Output: 'cherry'
print(my_list[-3]) # Output: 'apple'
❖An IndexError occurs if an index outside the valid range is used.
➢ Indexing and Slicing in Lists:
• Slicing: Slicing extracts a sub-sequence (a new list) from a list by
specifying a range of indices.
❖Basic Slicing Syntax: list[start:stop:step]
• start: The index where the slice begins (inclusive). If omitted, it defaults to 0 (the
beginning of the list).
• stop: The index where the slice ends (exclusive). If omitted, it defaults to the end of the
list.
• step: The increment between elements in the slice. If omitted, it defaults to 1.
numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
print(numbers[2:7]) # Output: [2, 3, 4, 5, 6] (elements from index 2 up to, but not including, index 7)
print(numbers[:5]) # Output: [0, 1, 2, 3, 4] (elements from the beginning up to, but not including, index 5)
print(numbers[5:]) # Output: [5, 6, 7, 8, 9] (elements from index 5 to the end)
print(numbers[::2]) # Output: [0, 2, 4, 6, 8] (every second element)
print(numbers[::-1]) # Output: [9, 8, 7, 6, 5, 4, 3, 2, 1, 0] (reverse the list)
❖Slicing creates a new list; it does not modify the original list.
❖Out-of-range indices in slicing are handled gracefully and do not raise an
error; the slice will simply include elements up to the valid boundary.
➢ Built in Functions Used on Lists:
• Built-in Functions Applicable to Lists:
1. len(list): Returns the number of items in a list.
2. max(list): Returns the item with the maximum value in a list.
3. min(list): Returns the item with the minimum value in a list.
4. sum(list): Returns the sum of all numeric items in a list.
5. sorted(iterable, key=None, reverse=False): Returns a new sorted list from the items in the
iterable (e.g., a list), leaving the original list unchanged.
6. list(iterable): Converts an iterable (like a tuple or set) into a list.
7. any(iterable): Returns True if any element of the iterable is true; otherwise, returns False.
8. all(iterable): Returns True if all elements of the iterable are true; otherwise, returns False.
9. enumerate(iterable, start=0): Returns an enumerate object, which yields pairs of index and
value.
10. filter(function, iterable): Constructs an iterator from elements of an iterable for which a
function returns true.
11. map(function, iterable, ...): Applies a given function to each item of an iterable and returns
a map object (an iterator).
12. zip(iterable1, iterable2, ...): Creates an iterator that aggregates elements from each of the
iterables.
➢ List Methods:
• List Methods (Functions Specific to List Objects):
1. [Link](item): Adds a single item to the end of the list.
2. [Link](iterable): Adds all items from an iterable (like another list) to the end
of the list.
3. [Link](index, item): Inserts an item at a specified position.
4. [Link](item): Removes the first occurrence of a specified item from the list.
5. [Link](index=-1): Removes and returns the item at a given index (defaults to
the last item).
6. [Link](): Removes all items from the list.
7. [Link](item, start=0, end=None): Returns the index of the first occurrence of
a specified item.
8. [Link](item): Returns the number of times a specified item appears in the list.
9. [Link](key=None, reverse=False): Sorts the list in place (modifies the original
list).
10. [Link](): Reverses the order of elements in the list in place.
11. [Link](): Returns a shallow copy of the list.
➢ The del Statement:
• The del statement in Python is used to remove elements from a list by
specifying their index or a slice (range of indices). Unlike the pop()
method, del does not return the removed element(s). It directly
modifies the list in place.
• Use of del statement with lists:
1. Deleting a single element by index:
my_list = [10, 20, 30, 40, 50]
del my_list[2] # Deletes the element at index 2 (which is 30)
print(my_list) #Output:[10, 20, 40, 50]
2. Deleting a slice of elements:
my_list = [10, 20, 30, 40, 50, 60]
del my_list[1:4] # Deletes elements from index 1 (inclusive) to 4 (exclusive)
print(my_list) #Output:[10, 50, 60]
3. Deleting the entire list:
my_list = [1, 2, 3]
del my_list
# print(my_list) # This would raise a NameError as the list no longer exists
➢ The del Statement:
• Key characteristics of del on lists:
1. In-place modification: del directly alters the existing list object.
2. No return value: Unlike pop(), del does not return the deleted
element(s).
3. Index-based removal: It relies on the index or slice of the
elements to be removed.
4. Error handling: If an invalid index is provided, an IndexError will
be raised. If the list itself is deleted and then referenced, a
NameError will occur.