Lists

What Are Lists?

  • Lists in Python are ordered collections of items that can store multiple values in a single variable.

Creating a List:

  • You can create a list using square brackets [] or the list() constructor.

    python
    list1 = [4, 8, 7, 6, 9]
    list2 = list([4, 8, 7, 6, 9])
    

Items in a List:

  • Items in a list can be of any datatype: integers, floats, strings, booleans, etc.

    python
    list1 = ["Apple", 54, 87.36, True]
    print(list1)  
    • Output: ['Apple', 54, 87.36, True]

Accessing Items:

  • Lists are ordered collections, so you can access items using their index (starting from 0).

    python
    list1 = ["Apple", 54, 87.36, True]
    print(list1[0])  # Output: Apple
    print(list1[1])  # Output: 54
    print(list1[2])  # Output: 87.36
    print(list1[3])  # Output: True
    

Updating Items:

  • You can update items in a list using their index and the assignment operator.

    python
    list1 = ['apple', 'banana', 'cherry', 'fig']
    list1[2] = 'orange'
    print(list1)  # Output: 
    • Output: ['apple', 'banana', 'orange', 'fig']

List Operations:

  • Lists support many operations such as appending, removing, sorting, and more.
  • Some common list methods include:
    • append(): Adds an item to the end.
    • clear(): Removes all items.
    • copy(): Returns a copy of the list.
    • count(): Returns the number of occurrences of an item.
    • extend(): Adds elements from another list.
    • index(): Returns the index of the first occurrence of an item.
    • insert(): Inserts an item at a given position.
    • pop(): Removes the item at a given position.
    • remove(): Removes the first occurrence of an item.
    • reverse(): Reverses the order of the list.
    • sort(): Sorts the list.

Summary:

  • Lists are versatile and powerful for storing and managing collections of items in Python. They support a wide range of operations and can contain any datatype. Practice creating, accessing, and modifying lists to become proficient in using them!