Python list is a mutable, ordered, and iterable collection of elements. Lists can contain items of different data types, such as integers, floats, strings, and even other lists or custom objects. Lists are a versatile and widely used data structure in Python for organizing and processing data.
How to Create a List
You can create a list by enclosing a comma-separated sequence of items within square brackets [].
# Creating a list with integers
numbers = [1, 2, 3, 4, 5]
# Creating a list with mixed data types
mixed_list = [1, "hello", 3.14, [1, 2, 3]]
print(mixed_list)
Output
[1, 'hello', 3.14, [1, 2, 3]]
How to access list elements
You can access list elements by their index, starting from 0 for the first item using the square brackets [].
# Creating a list with integers
numbers = [1, 2, 3, 4, 5]
# Creating a list with mixed data types
mixed_list = [1, "hello", 3.14, [1, 2, 3]]
print(mixed_list[0])
print(mixed_list[1])
Output
1
hello
Modify list elements using their index
numbers = [1, 2, 3, 4, 5]
numbers[0] = 11
print(numbers)
Output
[11, 2, 3, 4, 5]
Adding items to the list using the append() method or the + operator
numbers = [1, 2, 3, 4, 5]
numbers.append(6)
print(numbers)
Output
[11, 2, 3, 4, 5]
Removing elements from the list
You can remove elements from the list using the remove() method, del statement, or pop() method.
numbers = [1, 2, 3, 4, 5]
numbers.remove(2)
del numbers[0]
popped_item = numbers.pop()
print(numbers)
print(popped_item)
Output
[3, 4]
5
Use list comprehensions to create new lists based on existing lists
numbers = [1, 2, 3, 4, 5]
squares = [number**2 for number in numbers]
print(squares)
Output
[1, 4, 9, 16, 25]
Lists in Python are flexible and can be used for various purposes, such as storing and processing data, organizing objects, and implementing data structures like stacks and queues.