Python List with example

In Python, a list is a collection of ordered and mutable elements, enclosed in square brackets [ ]. Lists can contain any type of data, such as integers, floats, strings, and even other lists.

Here is an example of how to create a simple list in Python:

my_list = [1, 2, 3, 4, 5]

In this example, we have created a list called my_list that contains the integers 1 through 5.

We can also create a list with different types of data:

mixed_list = [1, 'apple', 3.14, True]

In this example, we have created a list called mixed_list that contains an integer, a string, a float, and a boolean value.

We can access individual elements in a list using their index position, which starts from 0. For example:

print(my_list[0])   # Output: 1
print(mixed_list[1])   # Output: 'apple'

We can also modify elements in a list by assigning a new value to a specific index:

my_list[3] = 100
print(my_list)   # Output: [1, 2, 3, 100, 5]

We can add new elements to the end of a list using the append() method:

my_list.append(6)
print(my_list)   # Output: [1, 2, 3, 100, 5, 6]

We can also insert a new element at a specific index using the insert() method:

my_list.insert(2, 50)
print(my_list)   # Output: [1, 2, 50, 3, 100, 5, 6]

We can remove elements from a list using the remove() method:

my_list.remove(3)
print(my_list)   # Output: [1, 2, 50, 100, 5, 6]

We can also remove the last element in a list using the pop() method:

my_list.pop()
print(my_list)   # Output: [1, 2, 50, 100, 5]

These are just a few examples of what you can do with Python Lists. There are many more built-in methods and operations available that you can use to manipulate and work with lists in Python.

Leave a Reply