Skip to content

Creating a list

# This creates a list of numbers from 1 to 10
my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

# This creates a list of strings
colors = ['red', 'green', 'blue']

# This creates an empty list
empty_list = []

Accessing elements of a list

# This will print the first element of the list (index 0)
print(my_list[0])

# This will print the last element of the list (index -1)
print(my_list[-1])

# This will print the second and third elements of the list (index 1 and 2)
print(my_list[1:3])

Modifying elements of a list

# This will change the second element of the list (index 1) to 'orange'
colors[1] = 'orange'

# This will add a new element 'purple' to the end of the list
colors.append('purple')

# This will insert a new element 'yellow' at index 1
colors.insert(1, 'yellow')

Removing elements from a list

# This will remove the last element of the list
colors.pop()

# This will remove the element at index 1
colors.pop(1)

# This will remove the first occurrence of the element 'red'
colors.remove('red')

Iterating over a list

# This will print all the elements of the list
for color in colors:
    print(color)

# This will print the index and element for each item in the list
for i, color in enumerate(colors):
    print(f"{i}: {color}")

Sorting a list

# This will sort the list in ascending order
colors.sort()

# This will sort the list in descending order
colors.sort(reverse=True)

Reversing a list

# This will reverse the order of the elements in the list
colors.reverse()

Finding the length of a list

# This will print the number of elements in the list
print(len(colors))

Using list comprehension

# This will create a new list with the squares of all the elements in my_list
squares = [x**2 for x in my_list]

# This will create a new list with the squares of all the even elements in my_list
even_squares = [x**2 for x in my_list if x % 2 == 0]

Using the map function

# This will create a new list with the squares of all the elements in my_list using the map function
squares = list(map(lambda x: x**2, my_list))