When learning Python, one of the important concepts is Lists.
Imagine you want to store five student names. Instead of creating five separate variables, Python allows us to store all those values in a single variable using a list.
1. What is a List?
A list is a built-in Python data structure used to store multiple values in a single variable.
Syntax:
students = ["Raja", "Arun", "Kumar", "Priya"]
Here:
-
studentsis the list variable. - Each value is called an element.
- Elements are separated by commas.
- Square brackets
[]are used to create a list.
2. Accessing List Elements
Python lists use zero-based indexing.
That means the first element starts at index 0.
students = ["Raja", "Arun", "Kumar"]
print(students[0]) # Raja
print(students[1]) # Arun
print(students[2]) # Kumar
We can also use negative indexing to access elements from the end.
print(students[-1]) # Kumar
print(students[-2]) # Arun
3. Lists Are Mutable
One important feature of Python lists is that they are mutable.
Mutable means we can modify the elements after creating the list.
students = ["Raja", "Arun", "Kumar"]
students[0] = "Megal"
print(students)
Output:
['Megal', 'Arun', 'Kumar']
Here, we changed the first element without creating a new list.
4. Adding Elements to a List
Python provides different methods to add elements.
append(): Adds an element at the end.
students.append("Priya")
insert(): Adds an element at a specific index.
students.insert(1, "Karthik")
5. Removing Elements
We can remove elements using different methods.
remove(): Removes a specified value.
students.remove("Arun")
pop(): Removes an element using its index. If no index is given, it removes the last element.
students.pop()
students.pop(0)
clear(): Removes all elements.
students.clear()
6. Finding the Length of a List
The len() function returns the total number of elements.
numbers = [10, 20, 30, 40]
print(len(numbers))
Output:
4
7. Looping Through a List
We can use a for loop to access every element.
students = ["Raja", "Arun", "Kumar"]
for student in students:
print(student)
Output:
Raja
Arun
Kumar
8. Lists Can Store Different Data Types
Unlike some strictly typed collections, Python lists can contain different types of values.
data = ["Raja", 22, 7.5, True]
print(data)
Here, the list contains a string, integer, float and boolean.
Conclusion
Python lists make it easier to store, access, modify and manage multiple values.
Top comments (0)