In Python, a list is a built-in data structure that allows you to store and manipulate a collection of items. Lists are ordered, mutable (modifiable), and can contain elements of different data types. You can think of a list as a sequence of values enclosed in square brackets
[ ], with each value separated by a comma.
Here’s an example of a Python list:
my_list = [1, 2, 3, 'four', 5.0]
In this example,
my_list contains five elements: an integer (
1), another integer (
2), a third integer (
3), a string (
'four'), and a float (
You can access individual elements of a list by their index. Python uses zero-based indexing, so the first element is at index
0, the second element at index
1, and so on. For example, to access the third element in
my_list, you would use
Lists in Python are mutable, meaning you can modify their contents. You can change the value of an element by assigning a new value to a specific index. For example,
my_list = 10 would change the first element of
You can perform various operations on lists, such as adding elements, removing elements, slicing, concatenating, sorting, and more. Python provides a rich set of built-in methods and functions to manipulate lists.
Here are a few examples of common list operations:
my_list = [1, 2, 3, 4, 5] # Append an element to the end of the list my_list.append(6) # my_list is now [1, 2, 3, 4, 5, 6] # Remove an element from the list my_list.remove(3) # my_list is now [1, 2, 4, 5, 6] # Get the length of the list length = len(my_list) # length is 5 # Access a sublist (slice) of the list sublist = my_list[1:4] # sublist is [2, 4, 5] # Concatenate two lists other_list = [7, 8, 9] concatenated = my_list + other_list # concatenated is [1, 2, 4, 5, 6, 7, 8, 9] # Sort the list my_list.sort() # my_list is now [1, 2, 4, 5, 6]
These are just a few examples of what you can do with lists in Python. Lists are versatile and widely used in Python programs to store and manipulate collections of data.