List and Tuple

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'])
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi阅读 7,486评论 0 10
  • 如今有很多孩子因为在家长的过度宠溺下,完全没有了时间的概念,做事拖拉,小事拖泥带水,大事遥遥无期。有些孩子从小就养...
    人海中的沙子阅读 1,151评论 1 8
  • 今天想给大家简单说一下咱们脸蛋护理有几个部分。我发现很多宝贝护肤都是简单的涂一下水乳,并不知道哪个东西修护什么地方...
    大Lei蕾阅读 350评论 0 0