(toc)


What is a List?

A list is an ordered collection of items that can store multiple data types such as integers, strings, floats, or even other lists. Lists in Python are mutable, meaning you can modify their elements after creation.


Creating a List

Lists are defined using square brackets [ ], with items separated by commas.


# Examples of lists numbers = [1, 2, 3, 4, 5] fruits = ["apple", "banana", "cherry"] mixed = [1, "hello", 3.5, True]

Accessing Elements in a List

You can access elements in a list using their index. Python uses zero-based indexing, meaning the first element is at index 0.


fruits = ["apple", "banana", "cherry"] # Access elements print(fruits[0]) # Output: apple print(fruits[2]) # Output: cherry

You can also use negative indexing to access elements from the end of the list.


print(fruits[-1]) # Output: cherry print(fruits[-2]) # Output: banana

Modifying a List

Lists are mutable, so you can change their content.


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

List Methods

Python lists come with several built-in methods to perform various operations.

1. Adding Elements

  • append(item): Adds an item to the end of the list.
  • insert(index, item): Inserts an item at a specific position.

fruits = ["apple", "banana"] fruits.append("cherry") # Add to the end print(fruits) # Output: ['apple', 'banana', 'cherry'] fruits.insert(1, "blueberry") # Add at index 1 print(fruits) # Output: ['apple', 'blueberry', 'banana', 'cherry']

2. Removing Elements

  • remove(item): Removes the first occurrence of an item.
  • pop(index): Removes and returns the item at the specified index.
  • clear(): Removes all elements from the list.

fruits = ["apple", "banana", "cherry"] fruits.remove("banana") print(fruits) # Output: ['apple', 'cherry'] fruits.pop(0) # Remove the first element print(fruits) # Output: ['cherry'] fruits.clear() # Empty the list print(fruits) # Output: []

3. Sorting and Reversing

  • sort(): Sorts the list in ascending order.
  • reverse(): Reverses the order of the list.

numbers = [3, 1, 4, 2] numbers.sort() # Sort in ascending order print(numbers) # Output: [1, 2, 3, 4] numbers.reverse() # Reverse the list print(numbers) # Output: [4, 3, 2, 1]

Iterating Through a List

You can use a loop to go through all elements in a list.


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

Output:
apple
banana
cherry


Checking for an Item in a List

Use the in keyword to check if an item exists in a list.


fruits = ["apple", "banana", "cherry"] if "banana" in fruits: print("Banana is in the list")

Output:
Banana is in the list


Slicing a List

Slicing allows you to extract a portion of a list by specifying a range of indices.


fruits = ["apple", "banana", "cherry", "date", "fig"] # Slice from index 1 to 3 (exclusive) print(fruits[1:4]) # Output: ['banana', 'cherry', 'date'] # Slice with step print(fruits[::2]) # Output: ['apple', 'cherry', 'fig']

Copying a List

To create a copy of a list, use the copy() method or slicing.


fruits = ["apple", "banana", "cherry"] # Using copy() copy_fruits = fruits.copy() # Using slicing copy_fruits_2 = fruits[:]

Nested Lists

Lists can contain other lists, allowing you to create multi-dimensional structures.


matrix = [ [1, 2, 3], [4, 5, 6], [7, 8, 9] ] print(matrix[1][2]) # Access row 1, column 2 (Output: 6)

Common List Operations

Here are some additional operations you can perform on lists:

1. Finding the Length


numbers = [1, 2, 3] print(len(numbers)) # Output: 3

2. Counting Occurrences


numbers = [1, 2, 3, 2, 2] print(numbers.count(2)) # Output: 3

3. Combining Lists


list1 = [1, 2] list2 = [3, 4] combined = list1 + list2 print(combined) # Output: [1, 2, 3, 4]

4. Repeating Lists


numbers = [1, 2] print(numbers * 3) # Output: [1, 2, 1, 2, 1, 2]


List Methods

Python lists come with several useful methods to manipulate the list. Here are some commonly used ones:

  • append(): Adds an element to the end of the list.


    fruits = ["apple", "banana"] fruits.append("cherry") print(fruits) # Output: ['apple', 'banana', 'cherry']
  • insert(): Adds an element at a specific index.


    fruits = ["apple", "banana"] fruits.insert(1, "blueberry") print(fruits) # Output: ['apple', 'blueberry', 'banana']
  • remove(): Removes the first occurrence of a value.


    fruits = ["apple", "banana", "cherry"] fruits.remove("banana") print(fruits) # Output: ['apple', 'cherry']
  • pop(): Removes an element at a given index (or the last element if no index is specified).


    fruits = ["apple", "banana", "cherry"] fruits.pop(1) print(fruits) # Output: ['apple', 'cherry']
  • clear(): Removes all elements from the list.


    fruits = ["apple", "banana", "cherry"] fruits.clear() print(fruits) # Output: []
  • index(): Returns the index of the first occurrence of a value.


    fruits = ["apple", "banana", "cherry"] print(fruits.index("banana")) # Output: 1
  • sort(): Sorts the list in ascending order (by default).


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

Leave a Reply