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

Python Lists

Python Lists - CodesFamily

Python Lists

Lists are one of the most versatile and widely used data structures in Python. They allow you to store multiple values in a single variable.

Creating a List


# Creating a list of numbers
numbers = [1, 2, 3, 4, 5]

# Creating a list with mixed data types
mixed_list = [1, "Hello", 3.14, True]

print(numbers)
print(mixed_list)
        

Accessing List Elements


fruits = ["Apple", "Banana", "Cherry"]

print(fruits[0])  # First element
print(fruits[-1])  # Last element
        

Modifying a List


fruits = ["Apple", "Banana", "Cherry"]
fruits[1] = "Mango"  # Changing an element
print(fruits)
        

Adding and Removing Elements


fruits.append("Orange")  # Adding an item
print(fruits)

fruits.remove("Apple")  # Removing an item
print(fruits)
        

List Slicing


numbers = [0, 1, 2, 3, 4, 5, 6, 7]
print(numbers[2:5])  # Output: [2, 3, 4]
print(numbers[:4])   # Output: [0, 1, 2, 3]
print(numbers[3:])   # Output: [3, 4, 5, 6, 7]
        

Looping Through a List


fruits = ["Apple", "Banana", "Cherry"]
for fruit in fruits:
    print(fruit)
        

Checking if an Item Exists


fruits = ["Apple", "Banana", "Cherry"]
if "Apple" in fruits:
    print("Yes, Apple is in the list")
        

Sorting a List


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

List Comprehension


squares = [x**2 for x in range(5)]
print(squares)  # Output: [0, 1, 4, 9, 16]
        

Conclusion

Lists are an essential part of Python programming. They provide a powerful way to store and manipulate data efficiently.