In addition to strings, python has two types of sequence structures, ** tuples ** and ** lists **, and can have 0 or more elements. The difference from the character string is that the element may have a different type.
Tuples are immutable, and when you substitute an element, it cannot be rewritten as if it had been baked.
It is mutable and allows you to delete and insert elements.
The list is suitable when you want to manage the elements in order, especially when the order and contents may change. Unlike strings, lists are mutable and can be modified directly.
The list separates zero or more elements with commas and encloses them in square brackets.
>>> empty_list = []
>>> weekdays=['Monday','Tuesday','Wednsday','Thursday','Friday']
>>> another_empty_list=list()#list()Empty list in function[]Can be created.
>>> another_empty_list
[]
#The character string is converted into a character string list for each character.
>>> list('cat')
['c', 'a', 't']
#Convert tuples to lists
>>> a_tuple=('ready','fire','aim')
>>> list(a_tuple)
['ready', 'fire', 'aim']
>>> birthday="1/4/1995"
#split()If you use a function, it will be separated by a separator and made into a list.
>>> birthday.split("/")
['1', '4', '1995']
>>> splitme="a/b//c/d//e"
#If the separators are continuous, an empty string is created as a list element.
>>> splitme.split('/')
['a', 'b', '', 'c', 'd', '', 'e']
>>> splitme="a/b//c/d///e"
>>> splitme.split('//')
['a/b', 'c/d', '/e']
Individual elements can be extracted from the list by specifying the offset as with the character string.
>>> marxes=["TTTTTT","aaaa","bbbb"]
>>> marxes[0]
'TTTTTT'
>>> marxes[1]
'aaaa'
>>> marxes[2]
'bbbb'
>>> marxes[-1]
'bbbb'
>>> marxes[-2]
'aaaa'
>>> marxes[-3]
'TTTTTT'
#The offset must be valid in the list of targets. (It must be a position that has already been assigned.)
>>> marxes[-34]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: list index out of range
>>> small_birds=["a","b"]
>>> extinct_birds=["c","d","e"]
>>> carol_birds=["f","g","h","i"]
>>> all_birds=[small_birds,extinct_birds,"AAA",carol_birds]
>>> all_birds#List of lists
[['a', 'b'], ['c', 'd', 'e'], 'AAA', ['f', 'g', 'h', 'i']]
>>> all_birds[0]
['a', 'b']
#[1]Is all_The second element of birds,[0]Points to the first element of its built-in list.
>>> all_birds[1][0]
'c'
Again, it must be valid in the list offset target list.
>>> marxes=["TTTTTT","aaaa","bbbb"]
>>> marxes[2]=["CCCC"]
>>> marxes[2]="CCCC"
>>> marxes
['TTTTTT', 'aaaa', 'CCCC']
>>> marxes[0:2]
['TTTTTT', 'aaaa']
#Slices can specify steps other than 1.
>>> marxes[::2]
['TTTTTT', 'CCCC']
>>> marxes[::-2]
['CCCC', 'TTTTTT']
#Reverse the list.
>>> marxes[::-1]
['CCCC', 'aaaa', 'TTTTTT']
I entered Chapter 4, but I was sleepy, so I did it moderately today.
"Introduction to Python3 by Bill Lubanovic (published by O'Reilly Japan)"
Recommended Posts