List in Python
In Python, a list is a built-in data structure that allows us to store a collection of items in a single variable. Lists are ordered, mutable, and can contain elements of different data types, including other lists.
A list is defined using square brackets []
, with each element separated by a comma. For example, we can create a list of integers like this:
my_list = [1, 2, 3, 4, 5]
We can also create a list of strings:
my_list = ['apple', 'banana', 'cherry']
We can access individual elements of a list using their index. The index of the first element in the list is 0, and the index of the last element is len(my_list) - 1
. For example, to access the first element of the my_list
list above, we can do:
first_element = my_list[0]
We can also modify individual elements of a list by assigning a new value to their index:
my_list[1] = 'orange'
We can add new elements to a list using the append()
method:
my_list.append(6)
We can remove elements from a list using the remove()
method:
my_list.remove(4)
We can also use various built-in functions and methods to manipulate lists, such as len()
, sort()
, reverse()
, and more.
Overall, lists are a versatile and useful data structure in Python, and they are commonly used in many programming tasks.
Apply for Python Certification!
https://www.vskills.in/certification/certified-python-developer