Lists in Python

A list is an ordered, mutable collection of items in Python. Lists allow storing multiple values in a single variable and provide powerful methods for manipulation.


1. Creating Lists

Lists are created using square brackets [] and can contain different data types.

Example:

fruits = ["apple", "banana", "cherry"]
numbers = [1, 2, 3, 4, 5]
mixed = ["Python", 3.14, True]
print(fruits, numbers, mixed)

Output:

['apple', 'banana', 'cherry'] [1, 2, 3, 4, 5] ['Python', 3.14, True]

2. Accessing List Elements

List elements are indexed, starting from 0.

Example:

fruits = ["apple", "banana", "cherry"]
print(fruits[0])   # First item
print(fruits[-1])  # Last item

Output:

apple
cherry

3. Slicing Lists

Retrieve a part of a list using slicing.

Example:

numbers = [10, 20, 30, 40, 50]
print(numbers[1:4])   # Elements from index 1 to 3
print(numbers[:3])    # First 3 elements
print(numbers[::-1])  # Reverse the list

4. Modifying Lists

Lists are mutable, meaning their elements can be changed.

Example:

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

5. Adding and Removing Elements

Adding Elements

fruits = ["apple", "banana"]
fruits.append("cherry")  # Add at end
fruits.insert(1, "orange")  # Insert at index 1
print(fruits)

Removing Elements

fruits.remove("banana")  # Remove by value
popped = fruits.pop()  # Remove last item
print(fruits, popped)

6. Looping Through a List

Example:

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

7. List Comprehensions

List comprehensions provide a concise way to create lists.

Example:

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

8. Sorting and Reversing Lists

Example:

numbers = [5, 2, 9, 1, 5, 6]
numbers.sort()  # Sort ascending
print(numbers)
numbers.reverse()  # Reverse order
print(numbers)

9. Checking Membership

Example:

fruits = ["apple", "banana", "cherry"]
print("banana" in fruits)  # Output: True
print("grape" not in fruits)  # Output: True

10. Copying Lists

Avoid modifying the original list unintentionally.

Example:

original = [1, 2, 3]
copy1 = original.copy()
copy2 = list(original)
copy3 = original[:]
print(copy1, copy2, copy3)

11. List Methods Summary

MethodDescription
append(x)Adds x to the end of the list
insert(i, x)Inserts x at index i
remove(x)Removes first occurrence of x
pop(i)Removes and returns element at index i (default: last)
sort()Sorts list in ascending order
reverse()Reverses the order of elements
copy()Creates a shallow copy of the list

12. Summary

Lists store multiple values in a single variable.
Lists are mutable, meaning they can be modified.
List operations include indexing, slicing, adding, removing, sorting, and looping.
List comprehensions provide a concise way to generate lists.

Leave a Reply

Your email address will not be published. Required fields are marked *

Scroll to Top