Python
Lists are an important data type in Python that allow you to store multiple values in a single place. They are similar to arrays in other programming languages, but have some additional features that make them more flexible.
To create a list, you can use square brackets and separate each item with a comma. For example:
my_list = [1, 2, 3, 4]
You can also create a list using the list()
function:
my_list = list([1, 2, 3, 4])
Lists can contain any data type, including other lists. For example:
my_list = [1, 'a string', 3.14, ['a', 'nested', 'list']]
You can access items in a list using an index. Like strings, lists are 0-indexed, meaning that the first item in the list has an index of 0. For example, to access the second item in the list my_list, you would use my_list[1]
. You can also use negative indices to access items from the end of the list. For example, my_list[-1]
would return the last item in the list.
With a nested list, we can access the inner list by using double square brackets.
my_list = [1, 'a string', 3.14, ['a', 'nested', 'list']]
print(my_list[-1][1])
# Outputs 'nested'
You can modify items in a list by reassigning them to a new value using the assignment operator. For example, to change the second item in the list my_list, you could do the following:
my_list[1] = 'a new string'
You can also use the append()
method to add an item to the end of a list, or the insert()
method to add an item at a specific index. For example:
my_list.append(5)
my_list.insert(2, 'another string')
There are many other useful methods for working with lists in Python, including extend()
, pop()
, and remove()
. It is important to understand how to use lists effectively as they are a common data structure used in many different types of programs.