Python Lists With Code Examples
Python Lists are a data structure that is used to store multiple items. Square brackets are used to represent them in python [ ]. They can hold any data type including strings, numbers, and other lists. The list is stored in an order and they can be accessed through their index.
Approach
Consider an example where you create a list of your favorite fruits.
favorite_fruits = ["apple", "banana", "orange"]
In this list, you can access individual items by their index, which starts with zero for the first item.
Suppose you have to access the fruit apple, you will do it as follows
print(favorite_fruits[0])
Output
apple
Inbuilt methods
Here are some commonly used functions and methods that can be used with Python Lists:
len() - returns the number of items in the list.
append() - adds an item to the end of the list.
insert() - adds an item at a specific index in the list.
remove() - removes an item from the list.
pop() - removes and returns the item at a specific index in the list.
index() - returns the index of the first occurrence of a specified item in the list.
count() - returns the number of times a specified item appears in the list.
sort() - sorts the items in the list in ascending order.
reverse() - reverses the order of the items in the list.
clear() - removes all items from the list.
Here are some code examples of these Functions:
# create a list of numbers
numbers = [3, 1, 4, 1, 5, 9, 2, 6]
# print the length of the list
print(len(numbers)) # output: 8
# add an item to the end of the list
numbers.append(5)
# insert an item at a specific index
numbers.insert(0, 2)
# remove an item from the list
numbers.remove(1)
# remove and return an item at a specific index
popped_item = numbers.pop(3)
print(popped_item) # output: 5
# get the index of an item in the list
index = numbers.index(4)
print(index) # output: 3
# count the number of times an item appears in the list
count = numbers.count(5)
print(count) # output: 1
# sort the list in ascending order
numbers.sort()
# reverse the order of the list
numbers.reverse()
# remove all items from the list
numbers.clear()
Time and Space complexity
The time and space complexity of Python lists depends on the specific operation being performed.