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.
Here are some examples of how to create and manipulate lists in Python, along with explanations of each method and function:
numbers = [1, 2, 3, 4, 5]
words = ["apple", "banana", "cherry"]
mixed = [1, "apple", 3.14, [1, 2, 3]]
print(numbers[0]) # prints 1
print(words[1]) # prints "banana"
numbers[0] = 10
print(numbers) # prints [10, 2, 3, 4, 5]
words[1] = "orange"
print(words) # prints ["apple", "orange", "cherry"]
numbers.append(6)
print(numbers)
# prints [10, 2, 3, 4, 5, 6]
words.insert(1, "mango")
print(words)
# prints ["apple", "mango", "orange", "cherry"]
numbers.remove(3)
print(numbers)
# prints [10, 2, 4, 5, 6]
words.pop(2)
print(words)
# prints ["apple", "mango", "cherry"]
numbers.sort()
print(numbers)
# prints [2, 4, 5, 6, 10]
words.sort()
print(words)
# prints ["apple", "cherry", "mango"]
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)
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"]