Skip to content

Python Lists

Python Lists

In Python, a List is a versatile and mutable collection of items. Lists can contain elements of different data types, making them flexible for various use cases.

Creating Lists:

Lists are created using square brackets []. Elements within a list are separated by commas.


        numbers = [1, 2, 3, 4, 5]
        fruits = ['apple', 'orange', 'banana']
        mixed_list = [42, 'hello', True, 3.14]
    

Accessing Elements:

Elements in a list can be accessed using indexing. Indexing starts at 0.


        fruits = ['apple', 'orange', 'banana']
        first_fruit = fruits[0]  # 'apple'
        second_fruit = fruits[1]  # 'orange'
    

Modifying Lists:

Lists are mutable, meaning you can change their content by adding, removing, or modifying elements.


        fruits = ['apple', 'orange', 'banana']
        
        # Add an element
        fruits.append('grape')

        # Remove an element
        fruits.remove('orange')

        # Modify an element
        fruits[0] = 'pear'
    

List Operations:

Lists support various operations like concatenation, repetition, and length calculation.


        list1 = [1, 2, 3]
        list2 = ['a', 'b', 'c']

        # Concatenation
        combined_list = list1 + list2  # [1, 2, 3, 'a', 'b', 'c']

        # Repetition
        repeated_list = list1 * 2  # [1, 2, 3, 1, 2, 3]

        # Length
        length = len(combined_list)  # 6
    

List Methods:

Python provides built-in methods for lists, such as append(), pop(), sort(), and more.


        numbers = [3, 1, 4, 1, 5, 9, 2]

        # Append an element
        numbers.append(6)

        # Remove and return the last element
        last_number = numbers.pop()

        # Sort the list
        numbers.sort()
    

Lists are a fundamental data structure in Python, offering flexibility and ease of use for handling collections of items.