Lists
List [ ]
They are containers around Data
List is an ordered sequence of objects that can be of any type
Any collection of items []
lists are a form of array. lists are mutable
li = [1, "a", 2, 'b', 2.5, True]
amazon_cart = [
'notebooks',
'sunglasses',
'toys',
'grapes']
print(amazon_cart[1]) # Indexing the list
print(amazon_cart[0::2]) # Slicing in list
amazon_cart[0] = 'laptop' # lists are mutable[replaceable], modifies the list
print(amazon_cart)
new_cart = amazon_cart.copy()
new_cart = amazon_cart[:] # [:] Creating a new copy or .copy()
Matrix
Matrix is a way to describe 2D lists or multi dimensional lists or Arrays.
Mostly used for machine learning.
matrix = [
[1, 5, 2],
[0, 1, [4]],
[3, 7, 9],
]
print(matrix[1][2]) # Outpu: [4]
Lists/Arrays Methods
basket = [1, 2, 3, 4, 5]
Unique Values
print(set(basket)) # Removes Duplicates[returns unique values]
Adding methods
basket.append(100) # adding at the last
print(basket)
basket.insert(4, 100) # inserting through index
print(basket)
basket.extend([100]) # extends the list and is iterable
print(basket)
Removing methods
basket.pop() # pops off end of the list
basket.pop(4) # removes through index
print(basket)
basket.remove(100) # remove the value given
print(basket)
basket.clear() # completely clears the list
print(basket)
letter = ['a', 'b', 'c', 'd', 'e', 'a']
print(letter.count('a')) # counts how many times value occurs in the list[through index or value]
print(letter.index('b')) # looks for the value and returns their index number
letter.sort() # sorts the list in an order
print(letter)
print(sorted(basket)) # works the same but produces a new list not modifies it
letter.reverse() # reverse the list
print(letter) # Output: ['a', 'a', 'b', 'c', 'd', 'e'] returns the original one
This version creates a new list, you use it for reversing. [for copying [:]]
print(letter[::-1])
To know whether a value exists in the data or not[can be used in strings, etc..]
print('x' in letter)
print("i" in 'Hi, I am Marwa') # in keyword for strings
Tricks in List
print(list(range(101))) # Output: gives the range from 0 to 100
sentence = " ".join(['hi', 'my', 'name', 'is', 'marwa']) # joins a list
print(sentence)
List Unpacking
a, b, c, *other, d = [1, 2, 3, 4, 5, 6, 7, 8, 9]
print(a)
print(b)
print(c)
print(other)
print(d)