List
Create a list
It doesn't like other OOP languages, Python allows mixed type elements in one list
example
//Code==========
L = ['Bin', 100, True]
print(L)
//Result==========
['Bin', 100, True]
Access a element from the list
Access element by index of elements, starting from 0
example
//Code==========
L = ['Bin', 100, True]
print(L[0])
//Result==========
Bin
Access a element from the list (reverse order)
The regular index is starting from 0, but reverse order is starting -1 as the last element of list
example
//Code==========
L = ['Bin', 100, True]
print(L[-3])
//Result==========
Bin
Add a new element to the list
There are two usefult methods, append()
and insert()
. Literally, append()
means append new element as the last one to the list, and insert()
means insert element to specific place, so that by using insert()
you need provide index and the value as element.
example
//Code==========
L = ['Bin', 100, True]
L.append('J')
print(L)
L.insert(0, 0)
print(L)
//Result==========
['Bin', 100, True, 'J']
[0, 'Bin', 100, True, 'J']
Remove a existing element from the list
There is only one method to remove the element from the list, pop()
. By providing a index of list, you can remove the element. it accepts reverse order index
example
//Code==========
L = ['Bin', 100, True]
L.pop(0)
print(L)
L.pop()
print(L)
//Result==========
[100, True]
[100]
Update a existing element from the list
For updating a existing element, just override the value by using access element operator
example
//Code==========
L = ['Bin', 100, True]
L[0] = 'Joanna'
print(L)
//Result==========
['Joanna', 100, True]
Tuple
Similar to List, but tuple is kind of const value, it doesn't allow to be modified.
Create a list
It doesn't like other OOP languages, Python allows mixed type elements in one list. To distinguish parentheses in arithmetic, when the tuple only has one element, the element should have suffix ,
, like ('100',)
, the result for the one-element tuple also has same format.
example
//Code==========
T = ('Bin', 100, True)
print(T)
T2 = (100,)
print(T2)
//Result==========
('Bin', 100, True)
(100,)
Updatable Tuple?
Even though the tuple is not updatable, but we can bind a updatable object as its element. Like Tuple(int, str, bool, list)
, Tuple[3] is pointing to a list object, which is unupdatable, but the element of the list object is updatable.
example
//Code==========
T = ('Bin', 100, True, ["Rain", "Snow"])
print(T)
L = T[3]
L[1] = "Wind"
print(T)
//Result==========
('Bin', 100, True, ['Rain', 'Snow'])
('Bin', 100, True, ['Rain', 'Wind'])