LIST DATA TYPE
LIST DATA TYPE
In Python, the list
data type is used to store a collection of items. It is an ordered and mutable data type, which means you can change its elements after it has been created. Lists are denoted by square brackets [ ]
and individual elements are separated by commas.
Here's an example of creating a list:
my_list = [1, 2, 3, 4, 5]
In this case, my_list
is a list containing the numbers 1, 2, 3, 4, and 5.
Lists can also contain elements of different data types, including other lists. Here's an example of a list with mixed data types:
mixed_list = [1, "hello", True, 2.5, [1, 2, 3]]
In addition to storing values, lists in Python have several built-in methods that allow you to perform various operations, such as adding or removing elements, accessing specific elements, sorting, and more.
Here are some common operations you can perform with lists:
# Accessing elements print(my_list[0])
Output: 1
# Modifying elements
my_list[2] = 10
print(my_list)
Output: [1, 2, 10, 4, 5]
# Appending elements
my_list.append(6)
print(my_list)
Output: [1, 2, 10, 4, 5, 6]
# Removing elements
my_list.remove(2)
print(my_list)
Output: [1, 10, 4, 5, 6]
# Length of the list
print(len(my_list))
Output: 5
# Sorting the list
my_list.sort()
print(my_list)
Output: [1, 4, 5, 6, 10]
These are just a few examples of what you can do with lists in Python. They are versatile and widely used for various programming tasks due to their flexibility and functionality.
Comments
Post a Comment