Lists
List is ordered sequence of elements. 0 based index. List is a mutable object. instance of list class.
geting length
use len() function. it returns the number of the elements in the list.
geting values
use index to get element of a list. negative index also works and start counting from the end of list.
ids = [123, 23, 432, 345]
print(ids[0])
# 123
print(ids[2])
# 432
print(ids[-1])
# 345changing list element
first, get the element using index then asign a new value to it with the same index.
deleting element
use del keyword.
ids = [123, 23, 432, 345]
del ids[1]
print(ids)
# [123, 432, 345]operations mutates the list
any operatins including adding, changing or removing element from the list, python mutates the list instead of creating new object.
non existent element
returned IndexError when trying to access non existent element.
list methods
there are methods in list class.
- append - add element to the end of list
- pop - remove element from the end of list and return it. if you specify index, it will remove element from the specific index and return it.
- extend - add multiple element to the end of list
- insert - add element to the specific index
- remove - remove element from the list
- clear - remove all elements from the list
- sort - sort list in ascending order
- reverse - reverse the list
- index - return the index of the first occurence of the element
- count - return the number of occurences of the element
- copy - return a copy of the list
arithmatic operations
you can use built-in max, min and sum functions to get the max, min and sum of the list.
ratings = [2.5, 5.0, 4.3, 3.7]
print(max(ratings))
# 5.0
print(min(ratings))
# 2.5
print(sum(ratings))
# 15.5
avg_rating = sum(ratings) / len(ratings)
print(avg_rating)
# 3.875combining list
use + operator to combine two lists and return new merged list. under the hood, the __add__ method is implicitly called by python. It does not mutate two lists.
list slicing
use range inside square brackets to slice the list. for example, ids[1:3] will return a new list with elements from index 1 to index 3. But element of index 3 is not included.
todo: add the sequence indexing table
copy list
assigning a list to another variable actually copies the reference to the same list. so changing one list will change the other. To copy, use any of the following 3 methods.
- use slicing to get new list and assign it to new variable. for example
new_ids = ids[:] - use
copymethod to get new list and assign it to new variable. for examplenew_ids = ids.copy() - use
listconstructor to get new list and assign it to new variable. for examplenew_ids = list(ids)