Skip to main content

Data Structure: List

Let us start with an exercise to help us understand what is list in python.

Problem:

You are asked to store and process the marks of 5 students in a test. The marks are as follows:

Student 1: 85 Student 2: 90 Student 3: 78 Student 4: 92 Student 5: 88

You need to:

  • Find the average marks.
  • Identify the highest mark.
  • Indentify the lowest mark.
#Student Marks
student1 = 85
student2 = 90
student3 = 78
student4 = 92
student5 = 88

#Objective 1: Please calculate the average marks of above students
#Objective 2: Please find the highest and lowest marks

average = None
highest = None
lowest = None

#Hint: The function to calculate higest number from a group of numbers is max
#highest = max(num_1, num_2, num_3, ....., num_n)

#Hint: The function to calculate lowest number from a group of numbers is min
#lowest = min(num_1, num_2, num_3, ....., num_n)

print("Average Marks:", average)
print("Highest Marks:", highest)
print("Lowest Marks:", lowest)

Issues Without a List:

  • Tedious for Large Data: If there are 100 students, creating and managing 100 variables is impractical.
  • Repetition in Code: Operations like sum or max require repeatedly referencing individual variables.
  • Lack of Flexibility: Adding or removing students requires modifying the variable declarations and related code.
  • Hard to Maintain: Debugging and extending the code become difficult as the number of students grows.
#Are there any bug(s) in the code below. If yes please fix them.

#Student Marks
student1 = 85
student2 = 90
student3 = 78
student4 = 93
student5 = 88
student6 = 70
student7 = 70
student8 = 58
student9 = 76
student10 = 92
#Objective 1: Please calculate the average marks of above students
#Objective 2: Please find the highest and lowest marks

#Step-1: Identify the highest and lowest marks (without code) and write them in comments below
#Highest:
#Lowest:

average = None
highest = None
lowest = None

# To find the average:
average = (student1 + student2 + student3 + student4 + student5 + student6 + student4 + student7 + student8 + student9 + student10) / 9
print("Average Marks:", average)

# To find the highest mark:
highest = max(student1 , student2 , student3 , student5 , student6 , student7 , student8 , student9 , student10)
print("Highest Marks:", highest)

lowest = min(student1 , student2 , student3 , student4, student5 , student6 , student7 , student9 , student10)
print("Lowest Marks:", lowest)

Can you imagine write code to solve the above problem for 100 students? How about 1000 students!

##Using a List:

A list allows you to store all the marks in a single variable and perform operations efficiently:

# Store all marks in a list
marks = [85, 90, 78, 92, 88]

# To find the average:
average = sum(marks) / len(marks)

# To find the highest mark:
highest = max(marks)

print("Average Marks:", average)
print("Highest Marks:", highest)

Advantages of Using a List:

  • Compact and Readable Code: All marks are stored in a single structure.
  • Efficient Operations: Functions like sum, max, and len work directly on lists.
  • Scalability: Adding or removing marks is as simple as modifying the list (e.g., marks.append(95)).
  • Iteration: You can easily loop through the list for any custom processing.
  • And most importantly, it is much less prone to typos.

Why Lists Are Needed:

Rich Functionality: Lists come with built-in methods (e.g., sorting, slicing, reversing) that make data manipulation easier.

###1. Dynamic Size Python lists can grow or shrink dynamically, allowing us to add or remove items without specifying a fixed size beforehand.

# Start with an empty list
students = []

# Dynamically add student names
students.append("Alice")
students.append("Bob")
students.append("Charlie")

print("Students after adding:", students)

# Remove a student
students.remove("Bob")

print("Students after removing Bob:", students)

###2. Heterogeneous Data Lists can store different types of data (e.g., marks = [85, "A", True]).

# A list with different data types
student_info = ["Alice", 21, 85.5, True]

print("Student Name:", student_info[0]) # String
print("Age:", student_info[1]) # Integer
print("Score:", student_info[2]) # Float
print("Passed:", student_info[3]) # Boolean

###3. Rich Functionality Python lists have built-in methods that make data manipulation straightforward.

# List of marks
marks = [85, 90, 78, 92, 88]

# Sorting
sorted_marks = sorted(marks)
print("Sorted Marks:", sorted_marks)

# Slicing (get the top 3 marks)
top_marks = sorted_marks[-3:]
print("Top 3 Marks:", top_marks)

# Reversing
marks.reverse()
print("Reversed Marks:", marks)

Working with Lists

1. Creating Lists

A list in Python is created using square brackets [].

# Empty list
my_list = []

# List with integers
int_list = [1, 2, 3, 4]

# List with mixed data types
mixed_list = [1, "Hello", 3.5, True]

2. Accessing Items in a List

You can access elements using their index (0-based).

Just like in a string we can using either positve or negative indexing to access individual items in a string.

####Positive Indexing

  • Starts from 0 and counts up from the beginning of the list.
  • The first element is at index 0, the second element at index 1, and so on.

Example:

my_list = ["apple", "banana", "cherry", "date"]

# Access the first element
print(my_list[0]) # Output: apple

# Access the second element
print(my_list[1]) # Output: banana

# Access the fourth element
print(my_list[3]) # Output: date

####Negative Indexing

  • Starts from -1 and counts backwards from the end of the list.
  • The last element is at index -1, the second-to-last element at -2, and so on.

Example:

my_list = ["apple", "banana", "cherry", "date"]

# Access the last element
print(my_list[-1]) # Output: date

# Access the second-to-last element
print(my_list[-2]) # Output: cherry

# Access the fourth-to-last (i.e., first) element
print(my_list[-4]) # Output: apple

####Why Both Positive and Negative Indexing Are Useful

  1. Positive indexing is straightforward when you're accessing elements from the beginning of the list.

  2. Negative indexing is convenient when you're dealing with elements at the end of the list, especially if the list length is unknown.

Finding the Index with of an element in the list

Just like we can use an index to get an element from the list, we can use an index to get the element at that index.

To find the index of an item in a list, you can use the index() method in Python.

Syntax:

list.index(item, start, end)

  • item: The element whose index you want to find.
  • start (optional): The index to start the search (default is 0).
  • end (optional): The index to stop the search (default is the end of the list).

Basic Example:

fruits = ["apple", "banana", "cherry", "date", "banana"]

# Find the index of "banana"
index = fruits.index("banana")
print(index) # Output: 1

###Finding the Index with a Start and End Range

If the item appears multiple times, you can limit the search using the start and end parameters.

Example:

fruits = ["apple", "banana", "cherry", "date", "banana"]

# Find the index of "banana" after the first occurrence
index = fruits.index("banana", 2) # Start searching from index 2
print(index) # Output: 4

Time to code:

#Given the string: Print the first and last words of the string

text = "Python is an amazing programming language"


#Create a list of days of the week from Sunday to Saturday. Get the index of today's day

2. Updating Lists

You can change the value of specific items by referring to their index.

my_list = [1, 2, 3, 4]
print(my_list) # Output: [1, 2, 3, 4]
my_list[2] = 10 # Update the third item
print(my_list) # Output: [1, 2, 10, 4]

###3. Adding Items to a List

Using append():

  • Adds a single item to the end of the list.
my_list = [1, 2, 3]
my_list.append(4)
print(my_list) # Output: [1, 2, 3, 4]

Using extend():

  • Adds multiple items to the end of the list.
my_list = [1, 2]
my_list.extend([3, 4])
print(my_list) # Output: [1, 2, 3, 4]

Using insert():

  • Adds an item at a specific index.
my_list = [1, 2, 4]
my_list.insert(2, 3) # Insert 3 at index 2
print(my_list) # Output: [1, 2, 3, 4]

##Time to Code

####Problem 1: Grocery List Write a program to manage a grocery list:

  • Start with an empty list.
  • Add items one by one based on user input until they type "done".
  • Display the final list.
grocery_list = [] #Intializing grocery list

###Problem 2: Adding Items at Specific Positions

  • In the below list insert the color "yellow" at index 1.
  • Insert the color "orange" at the end of the list without using append().
colors = ["red", "blue", "green"]