## Tuesday 20 February 2024

### What are Sequences? And Lists In Python

What are Sequences?

In Python, a sequence is an ordered collection of items. Each item in a sequence is called an element, and these elements are assigned an index (position) starting from zero. This means you can access individual elements using their index.

Common Sequence Types

Python has several built-in sequence types. Here are the most important ones:

1. Strings:

• An ordered sequence of characters.

• Example: name = "Alice"

1. Lists:

• An ordered collection of items, which can be of different data types.

• Mutable: You can change, add, or remove elements after creation.

• Example: numbers = [1, 5, -2, 8]

1. Tuples:

• An ordered collection of items, similar to lists.

• Immutable: You cannot change the elements after creation.

• Example: coordinates = (10, 20)

1. Ranges:

• A sequence of numbers generated by the range() function. Useful for iterations.

• Example: numbers = range(1, 6) # Represents numbers 1, 2, 3, 4, 5

Why Sequences Matter

• Structured Data: Sequences let you organize data in a meaningful way, essential for solving problems and building applications.

• Iteration: They can be easily iterated over using loops (like for loops) to process their elements one by one.

• Slicing: You can extract specific sub-sequences (portions of a sequence) using slicing notation like my_sequence[start:end].

Lists: The Mutable Workhorses

Lists are one of the most fundamental and versatile data structures in Python. Here's why they're so important:

• Ordered: Lists maintain the order in which you insert elements. This is crucial when the sequence of items matters.

• Mutable: You can change the contents of a list even after it's created. You can add, remove, and modify elements at will.

• Heterogeneous: Lists can hold elements of different data types. You can store integers, strings, Booleans, even other lists within a single list!

Creating Lists

1. Square Brackets: The most common way:
Python
numbers = [1, 5, 20, -8]

2. list() Constructor: Useful for converting other iterables:
Python
coordinates_tuple = (5, 12)
coordinates_list = list(coordinates_tuple)

Key Operations

• Accessing Elements (Indexing):
Python
numbers = [10, 20, 30]
first_number = numbers[0# 10
second_number = numbers[1# 20

• Slicing: Extracting sub-lists
Python
middle_elements = numbers[1:3# [20, 30]

• append(): Adds a single element to the end.

• extend(): Adds multiple elements from another iterable.

• insert() : Inserts an element at a specific position

• Removing Elements:

• remove(): Removes the first occurrence of a value.

• pop(): Removes and returns the element at a specific index (or the last one by default).

• del: Deletes an element by its index.

• Checking Membership:
Python
if "milk" in shopping_items:
print("Milk is on the list")

• Iteration (Looping):
Python
for number in numbers:
print(number * 2)

Practical Example

Python

tasks = ["Write report", "Send emails", "Attend meeting"]

# Marking a task as done

Why Choose Lists

Lists are fantastic when you need:

• A collection of items where the order is important.

• To modify the collection (add, remove, rearrange) after creation.

• A structure to hold data of various types together.

Accessing and Modifying Elements

• Indexing ([ ]) Access individual elements by their zero-based index.
Python
numbers = [1, 5, 3]
first_number = numbers[0# first_number will be 1
numbers[2] = 10  # Changes the third element to 10

• Slicing ([:]) Extract a sub-list using the start:end:step notation. Remember, slicing creates a new list.
Python
letters = ['a', 'b', 'c', 'd']
middle_letters = letters[1:3# middle_letters will be ['b', 'c']

• append(element) Adds a single element to the end of the list.
Python
shopping_list.append("eggs")

• extend(iterable) Extends the list by adding elements from an iterable (like another list, tuple, or string).
Python
numbers = [1, 2, 3]
more_numbers = [4, 5]
numbers.extend(more_numbers)  # numbers will become [1, 2, 3, 4, 5]

• insert(index, element) Inserts an element at a specific index, shifting other elements to the right.
Python
colors = ["red", "green", "blue"]
colors.insert(1, "yellow"# colors will become ["red", "yellow", "green", "blue"]

Removing Elements

• remove(value) Removes the first occurrence of the specified value. Raises a ValueError if the value is not found.
Python
numbers = [1, 5, 2, 5]
numbers.remove(5# removes the first '5'

• pop([index]) Removes and returns the element at the specified index (defaults to the last element if no index is given).
Python
colors = ["red", "green", "blue"]
last_color = colors.pop()  # last_color will be "blue"

• del list_name[index] Deletes an element by its index. You can also use del to delete slices.

Other Important Operations

• len(list_name) Returns the length (number of elements) of the list.

• in and not in Check if an element exists in the list.
Python
if "apple" in fruits:
print("Found apple!")

• Iteration: Use for loops to process list elements.
Python
for color in colors:
print(color.upper())

• Sorting:

• list_name.sort() Sorts the list in place (modifies the original list).

• sorted(list_name) Returns a new sorted list without modifying the original.

Example Scenario

Python

todo_list = ["Buy groceries", "Study Python", "Water plants"]

print("Updated To-Do List:")

Others

• list.copy() Creates a shallow copy of the list.

Let's see an example:

Python

tasks = ["Finish project", "Call Sarah", "Learn Django"]

print("To-Do List:")

Example 1: Managing a Shopping List

Python

shopping_list = ["eggs", "bread", "milk", "bananas"]

new_item = input("What would you like to add to the list? ")
shopping_list.append(new_item)

# Print the updated list
for item in shopping_list:
print(item)

# Remove an item if you bought it
bought_item = input("Did you buy anything? If so, what? ")
if bought_item in shopping_list:
shopping_list.remove(bought_item)
print(f"Removed {bought_item} from the list.")
else:
print(f"{bought_item} is not on the list.")

Example 2: Calculating Numerical Statistics

Python

temperatures = [25.2, 28.5, 30.1, 26.7, 23.8]

# Calculate average temperature
average_temp = sum(temperatures) / len(temperatures)
print("Average temperature:", average_temp)

# Find minimum and maximum temperatures
min_temp = min(temperatures)
max_temp = max(temperatures)
print("Minimum temperature:", min_temp)
print("Maximum temperature:", max_temp)

Example 3: Word Frequency Analysis

Python

text = "This is a sample text for word frequency analysis.

This text contains some repeated words."

# Split the text into words and convert to lowercase
words = text.lower().split()

# Count the occurrences of each word
word_counts = {}
for word in words:
if word in word_counts:
word_counts[word] += 1
else:
word_counts[word] = 1

# Print the words and their frequencies
for word, count in word_counts.items():
print(f"{word}: {count}")

Example 4: Sorting and Filtering

Python

students = [
]

for student in students:
print(student)

# Filter students with grades above 80
passing_students = [student for student in students if student["grade"] > 80]
print("Passing students:")
for student in passing_students:
print(student)

Basic Concepts

• Q: Explain what lists are in Python and how they differ from tuples.

• A: Lists are ordered, mutable collections of items. They can hold elements of different data types. Tuples are similar to lists but are immutable, meaning their elements cannot be changed after creation.

• Q: Describe how to create an empty list and a list with initial values.

• A: You create an empty list using empty square brackets: my_list = []. To create a list with initial values, you place the values within the square brackets, separated by commas: numbers = [1, 5, 3, 8].

• Q: How do you access elements in a list and update their values?

• A: You access elements using zero-based indexing: first_item = my_list[0]. You update values directly by assigning to the index: my_list[2] = "new_value".

Operations and Functionality

• Q: Explain the difference between list.append() and list.extend() methods.

• A: append() adds a single element to the end of a list. extend() adds multiple elements from an iterable (like another list, string, or tuple) to the end of the list.

• Q: What is the purpose of the list.remove() method and how does it differ from list.pop()?

• A: remove() removes the first occurrence of a specified value from the list. pop() removes and returns the element at a given index (or the last element if no index is provided).

• Q: How do you sort a list in ascending or descending order?

• A: You use the list.sort() method to sort in ascending order: numbers.sort(). For descending order, you add the reverse=True argument: numbers.sort(reverse=True).

Scenarios and Problem-Solving

• Q: Given a list of numbers, how would you find the second largest number?

• A: One approach is to sort the list in descending order and then access the second element: numbers.sort(reverse=True); second_largest = numbers[1]. Alternatively, you can track the largest and second-largest numbers during a single iteration.

• Q: How would you remove duplicate elements from a list?

• A: One way is to create a new list and add only unique elements. Another efficient method is to convert the list to a set (which inherently stores unique elements) and then back to a list: unique_list = list(set(original_list)).

• Q: Can you explain what list slicing is and give an example?

• A: List slicing allows you to extract a sub-list using the notation list_name[start:end:step]. For example, middle_elements = my_list[1:4] would extract the elements from index 1 up to (but not including) index 4.

• list.append(x) Adds a single element (x) to the end of the list.
Python
numbers = [1, 2, 3]
numbers.append(4# numbers becomes [1, 2, 3, 4]

• list.insert(index, x) Inserts an element (x) at a specific index within the list.
Python
colors = ["red", "green"]
colors.insert(1, "blue"# colors becomes ["red", "blue", "green"]

• list.extend(iterable) Appends all the elements from an iterable (list, tuple, etc.) to the end of the list.
Python
numbers = [1, 2]
more_numbers = [3, 4, 5]
numbers.extend(more_numbers)  # numbers becomes [1, 2, 3, 4, 5]

Functions for Removing

• list.remove(x) Removes the first occurrence of a value (x) from the list. Raises a ValueError if the value is not found.
Python
letters = ['a', 'b', 'c', 'b']
letters.remove('b'# letters becomes ['a', 'c', 'b']

• list.pop([index]) Removes and returns the element at a given index (defaults to the last element if no index is given).
Python
colors = ["red", "green", "blue"]
last_color = colors.pop()  # last_color becomes "blue"

• list.clear() Removes all elements from the list, making it empty.
Python
my_list = [1, 2, 3]
my_list.clear()  # my_list becomes []

Information and Searching

• list.index(x) Returns the index of the first occurrence of a value (x) in the list. Raises a ValueError if not found.
Python
fruits = ["apple", "banana", "orange"]
banana_index = fruits.index("banana"

• list.count(x) Returns the number of times a value (x) appears in the list.
Python
numbers = [1, 5, 1, 3, 1]
count_of_1 = numbers.count(1# count_of_1 becomes 3

Sorting and Reversing

• list.sort() Sorts the elements of the list in ascending order (modifies the list in-place). Optionally takes reverse=True for descending order.
Python
numbers = [5, 2, 9, 1]
numbers.sort()  # numbers becomes [1, 2, 5, 9]

• list.reverse() Reverses the order of elements in the list (modifies the list in-place).
Python
colors = ["red", "green", "blue"]
colors.reverse()  # colors becomes ["blue", "green", "red"]

Others

• list.copy() Creates a shallow copy of the list.

Let's see an example:

Python

tasks = ["Finish project", "Call Sarah", "Learn Django"]

print("To-Do List:")