A list in Python is a collection of items that are ordered and changeable. Items in a list are separated by commas and enclosed in square brackets.
Features of List
- Lists are ordered: The items in a list have a definite order, and you can access them by their index.
- Lists are mutable: You can add, remove, and modify items in a list after it has been created.
- Lists can store multiple data types: Lists can store items of different data types, such as strings, integers, and other objects.
- Lists are dynamic: Lists can grow or shrink in size as needed.
Basic Operations
Here are some examples of how to create and manipulate lists in Python, along with explanations of each method and function:
Creating a list
numbers = [1, 2, 3, 4, 5]
words = ["apple", "banana", "cherry"]
mixed = [1, "apple", 3.14, [1, 2, 3]]
Accessing items in a list
print(numbers[0]) # prints 1
print(words[1]) # prints "banana"
Modifying items in a list
numbers[0] = 10
print(numbers) # prints [10, 2, 3, 4, 5]
words[1] = "orange"
print(words) # prints ["apple", "orange", "cherry"]
Adding items to a list
numbers.append(6)
print(numbers)
# prints [10, 2, 3, 4, 5, 6]
words.insert(1, "mango")
print(words)
# prints ["apple", "mango", "orange", "cherry"]
Removing items from a list
numbers.remove(3)
print(numbers)
# prints [10, 2, 4, 5, 6]
words.pop(2)
print(words)
# prints ["apple", "mango", "cherry"]
Sorting a list
numbers.sort()
print(numbers)
# prints [2, 4, 5, 6, 10]
words.sort()
print(words)
# prints ["apple", "cherry", "mango"]
Iteration
You can also use loops to iterate through the items in a list. Here's an example:
for num in numbers:
print(num)
This will print all the items in the numbers
list, one at a time.
You can also use the enumerate()
function to get the index and value of each item in a list:
for i, word in enumerate(words):
print(i, word)
List Methods
len(list)
: returns the number of elements in the list.
max(list)
: returns the maximum element in the list.
min(list)
: returns the minimum element in the list.
sum(list)
: returns the sum of elements in the list.
list.count(element)
: returns the number of occurrences of the element in the list.
list.extend(iterable)
: adds the elements of an iterable to the end of the list.
list.index(element)
: returns the index of the first occurrence of the element in the list.
list.reverse()
: reverses the elements of the list in place.
numbers = [2, 4, 5, 6, 10]
print(len(numbers)) # prints 5
print(max(numbers)) # prints 10
print(min(numbers)) # prints 2
print(sum(numbers)) # prints 27
print(numbers.count(5)) # prints 1
words = ["apple", "cherry", "mango"]
words2 = ["kiwi", "lemon"]
words.extend(words2)
print(words)
# prints ["apple", "cherry", "mango", "kiwi", "lemon"]
print(words.index("kiwi"))
# prints 3
words.reverse()
print(words)
# prints ["lemon", "kiwi", "mango", "cherry", "apple"]