Understanding Python Lists

Python lists are ordered, mutable collections of items. They are one of the most versatile data types in Python, allowing you to store a collection of items of any type, including other lists. Lists are defined using square brackets [] and can contain elements of different data types.

Creating Lists

Example: Lists with Different Data Types

# Creating lists with different data types
int_list = [1, 2, 3, 4, 5]
string_list = ["Karthick AG", "Durai", "Vijay", "John", "Praveen", "Williams"]
mixed_list = [1, "Hello", 3.14, True, None]
nested_list = [int_list, string_list, mixed_list]
print("Integer List:", int_list)
print("String List:", string_list)
print("Mixed List:", mixed_list)
print("Nested List:", nested_list)

Output

Integer List: [1, 2, 3, 4, 5]

String List: ['Karthick AG', 'Durai', 'Vijay', 'John', 'Praveen', 'Williams']

Mixed List: [1, 'Hello', 3.14, True, None]

Nested List: [[1, 2, 3, 4, 5], ['Karthick AG', 'Durai', 'Vijay', 'John', 'Praveen', 'Williams'], [1, 'Hello', 3.14, True, None]]

Explanation: In this example, we create different lists containing integers, strings, mixed data types, and even other lists (nested lists). Python lists can hold items of different data types, and nesting allows lists within lists.

Accessing List Elements

List elements can be accessed using their index, starting from 0 for the first element.

Example: Accessing Elements

# Accessing list elements
first_item = string_list[0]
last_item = string_list[-1]
nested_item = nested_list[1][2]
print("First Item:", first_item)
print("Last Item:", last_item)
print("Nested Item:", nested_item)

Output

First Item: Karthick AG

Last Item: Williams

Nested Item: Vijay

Explanation: We access elements using their indices. Negative indices start from the end (-1 is the last item). For nested lists, we use multiple indices to access the nested items.