Home HTML CSS JAVASCRIPT BOOTSTRAP Python Docker ML tutorial About us Privacy policy

Python Lists and List Operations

Python Lists and List Operations - CodesFamily

Python Lists and List Operations

Lists in Python are used to store multiple items in a single variable. They are ordered, mutable, and allow duplicate values.

Creating a List


# Creating a list of fruits
fruits = ["apple", "banana", "cherry"]
print(fruits)
        

Accessing List Items


fruits = ["apple", "banana", "cherry"]
print(fruits[0])  # Output: apple
print(fruits[-1])  # Output: cherry
        

Modifying a List


fruits = ["apple", "banana", "cherry"]
fruits[1] = "blueberry"
print(fruits)  # Output: ['apple', 'blueberry', 'cherry']
        

Adding Elements


fruits = ["apple", "banana"]
fruits.append("cherry")
print(fruits)  # Output: ['apple', 'banana', 'cherry']

fruits.insert(1, "blueberry")
print(fruits)  # Output: ['apple', 'blueberry', 'banana', 'cherry']
        

Removing Elements


fruits = ["apple", "banana", "cherry"]
fruits.remove("banana")
print(fruits)  # Output: ['apple', 'cherry']

fruits.pop()
print(fruits)  # Output: ['apple']
        

Looping Through a List


fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
    print(fruit)
        

List Comprehension


numbers = [x for x in range(10) if x % 2 == 0]
print(numbers)  # Output: [0, 2, 4, 6, 8]
        

Sorting a List


numbers = [4, 2, 9, 1, 5]
numbers.sort()
print(numbers)  # Output: [1, 2, 4, 5, 9]

numbers.sort(reverse=True)
print(numbers)  # Output: [9, 5, 4, 2, 1]
        

Conclusion

Lists are one of the most commonly used data structures in Python. Understanding list operations is crucial for effective programming.