Coding Lesson (4-8 Nov)
Monday
-
Tuesday
Continue studying on Kaggle. I learned about lists in Python. Lists helps you organize, for example you want to make a lists of flower species. To organize, you should use Python string. For example:
flowers = "pink primrose,hard-leaved pocket orchid,canterbury bells,sweet pea,english marigold,tiger lily,moon orchid,bird of paradise,monkshood,globe thistle"
print(type(flowers))
print(flowers)
<class 'str'>
pink primrose,hard-leaved pocket orchid,canterbury bells,sweet pea,english marigold,tiger lily,moon orchid,bird of paradise,monkshood,globe thistle
To make it easier to read, you can use square brackets ([]) and add comma.
flowers_list = ["pink primrose", "hard-leaved pocket orchid", "canterbury bells", "sweet pea", "english marigold", "tiger lily", "moon orchid", "bird of paradise", "monkshood", "globe thistle"]
print(type(flowers_list))
print(flowers_list)
<class 'list'>
['pink primrose', 'hard-leaved pocket orchid', 'canterbury bells', 'sweet pea', 'english marigold', 'tiger lily', 'moon orchid', 'bird of paradise', 'monkshood', 'globe thistle']
At first, we will see that nothing really change. But, there are a lot of tasks that you can more easily do with a list.
- get an item at a specified position (first, second, third, etc),
- check the number of items, and
- add and remove items.
Wednesday
Continue on lists, here is example that lists will make it easier.
Indexing
You can refer to any item in the list according to its position (first, second, third, etc). Here is how you do it:
print("First Entry:", flowers_list[0])
print("Second Entry:", flowers_list[3])
print("Third Entry:", flowers_list[9])
First Entry: pink primrose
Second Entry: sweet pea
Third Entry: globe thistle
Note: Python uses zero-based indexing.
Thursday
Slicing
You can pull a segment of lists (for instance, the first four entries or the last two entries). This is called slicing. For instance:
- to pull the first
x
entries, you use[:x]
, and - to pull the last
y
entries, you use[-y:]
.
print("First four entries:", flowers_list[:4])
print("Final two entries:", flowers_list[-2:])
First four entries: ['pink primrose', 'hard-leaved pocket orchid', 'canterbury bells', 'sweet pea']Final two entries: ['monkshood', 'globe thistle']
Comments
Post a Comment