Python - Lists

In Python, a list is a collection of ordered, mutable and heterogeneous elements. It is a data structure that allows you to store and manipulate a group of related values. Lists can contain elements of different data types, including integers, floats, strings, and other objects, making them very versatile.

A list is a collection of ordered and changeable elements, which can be of any data type. Lists are one of the most commonly used data structures in Python, as they allow you to store and manipulate data in a very flexible way.

In Python, lists are created using square brackets []. Here's an example of a simple list that contains a few integers:

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

Lists can contain elements of different data types, such as strings, integers, and even other lists:

my_list = [1, "hello", True, [5, 6, 7]]

To access individual elements of a list, you can use their index, which starts at 0. Here's an example of how to access the first element of a list:

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

You can also use negative indices to access elements from the end of the list:

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

To modify elements of a list, you can simply assign a new value to the desired index:

my_list = [1, 2, 3, 4, 5]
my_list[0] = 6
print(my_list)  # Output: [6, 2, 3, 4, 5]

You can also add new elements to a list using the append() method:

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

To insert an element at a specific index, you can use the insert() method:

my_list = [1, 2, 3, 4, 5]
my_list.insert(2, "hello")
print(my_list)  # Output: [1, 2, 'hello', 3, 4, 5]

To remove an element from a list, you can use the remove() method:

my_list = [1, 2, 3, 4, 5]
my_list.remove(3)
print(my_list)  # Output: [1, 2, 4, 5]

You can also use the pop() method to remove and return the last element of a list:

my_list = [1, 2, 3, 4, 5]
last_element = my_list.pop()
print(last_element)  # Output: 5
print(my_list)  # Output: [1, 2, 3, 4]

Lists can be sliced to create a new list containing a specific range of elements. Here's an example of how to create a new list containing the second through fourth elements of a list:

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

Finally, you can use the len() function to determine the length of a list:

list1, list2 = [123, 'xyz', 'zara'], [456, 'abc']
print "First list length : ", len(list1)
print "Second list length : ", len(list2)
#First list length :  3
#Second list length :  2