Python-Lists:
Till now we focused on how to store values in a variable. But how can we store
multiple values in a single variable?
Data Structures:
Data structures are containers that store multiple values in a single variable.
Example: storing names of students, marks of subjects, etc.
Why do we need Lists?
To store multiple items in one variable.
1. Lists:
# Example:
# Suppose you want to store marks of 5 students
marks = [85, 90, 78, 92, 88]
print("Student Marks:", marks)
print("Average Marks:", sum(marks)/len(marks))
● Lists are ordered, changeable (mutable), and allow duplicates.
● It is written with squared brackets [ ].
● We can modify even after creation of the lists.
● Creating a List:
fruits = ["apple", "banana", "cherry"]
print(fruits)
● Accessing the List:
print(fruits[0]) # First element
print(fruits[-1]) # Last element
● Changing values:
fruits[1] = "mango"
print(fruits)
● Adding and Removing Values:
[Link]("grape") # Add at end
[Link](1, "orange") # Add at position
print(fruits)
[Link]("apple") # Remove specific element
[Link]() # Removes last element
print(fruits)
● Looping Through Lists:
for fruit in fruits:
print(fruit)
● Checking if an item exists:
if "mango" in fruits:
print("Mango is in the list")
● Length of the List:
print(len(fruits))
What is Slicing? Why is it needed in python? Is it useful?
Slicing helps us work with subsets of data.
To extract parts of the list easily.
● Slicing a list :
print(fruits)
print(fruits[1:3]) # from index 1 to 2
print(fruits[:2]) # first two
print(fruits[2:]) # from index 2 to end
print(fruits[:-1]) # index from 2 to 1 reverse
print(fruits[::-1]) # prints in reverse order
● Built-in List Functions:
numbers = [5, 2, 9, 1]
print(max(numbers)) # largest element
print(min(numbers)) # smallest element
print(sum(numbers)) # sum of all elements
[Link]() # sorts ascending
print(numbers)
[Link]() # reverses list
print(numbers)
● Copying Lists :
list1 = [1, 2, 3]
list2 = list1 # both refer to same list
list3 = [Link]() # creates a new copy
[Link](4)
print(list1) # [1, 2, 3, 4]
print(list2) # [1, 2, 3, 4] same as list1
print(list3) # [1, 2, 3] remains unchanged
Real-life Example:
shopping_list = ["milk", "bread", "eggs"]
shopping_list.append("butter")
print("Updated shopping list:", shopping_list)
if "eggs" in shopping_list:
print("Don't forget to buy eggs!")