You will be an engineer in 100 days --Day 28 --Python --Basics of the Python language 4

Today is a continuation of the basics of Python.

Click here for the last time

You will be an engineer in 100 days --Day 27 --Python --Python Exercise 1

list

I'm sorry if it doesn't appear

You can handle special data forms within a programming language. That is the data structure such as dictionary type and list type.

Use [] square brackets to create list type data. Enter the data in the form of the data you want to store in the square brackets.

List-type values can have multiple elements. To put a lot of elements in the value of the list, connect them with commas.

** List type definition **

[] [Element, element, ...]

List example: [1,2,3]

#List type
l1 = [1,2,3,4,5]

#Empty list(I don't have an element yet)
l2 = []

print(l1)
print(l2)

[1,2,3,4,5] []

The list type is a data structure with multiple elements. There is no particular rule regarding the shape of the data that can be stored in the list type. You can enter any data.

a = [1,2,3,'4']
print(a)

[1, 2, 3, '4']

List elements can also be a mixture of different data types.

Be careful as it uses [] and can easily be mistaken for index. List types in the Python language are referenced using index.

** Browse list elements **

List type data [index value]

#Define a list inside a list
lis_lis = [[1,2,3],[4,5,6],[7,8,9]]
print(lis_lis)

#Eject with index
print(lis_lis[1][2])

[[1, 2, 3], [4, 5, 6], [7, 8, 9]] 6

You can store the list inside the list. In that case, it will be a multiple list, so you can also specify [] to retrieve You will write only the multiple parts.

Also, the index has a function called slice. Since you can specify the start, end, etc. The elements taken out also change depending on how they are sliced.

List type [index value]: Extract only one element. List type [start: end]: Multiple elements from start to end can be retrieved. List type [start:]: Multiple elements from the start to the end can be retrieved. List type [: end]: Multiple elements from the beginning to the end can be retrieved. List type [Start: End: Number of skips] You can retrieve multiple elements by skipping n from the start to the end.

a = [1,2,3]
#Extract the first element
print(a[0])
print(type(a[0]))

1 <class 'int'>

a = [1,2,3,4,5]
#Extract multiple elements(From 3rd to 4th)
print(a[2:4])
print(type(a[2:4]))

[3, 4] <class 'list'>

a = [1,2,3,4,5]
#Extract multiple elements(From second to last)

print(a[1:])

#Extract multiple elements(From the first to the third)
print(a[:3])

[2, 3, 4, 5] [1, 2, 3]

The order of the elements is important in the list. Slices work with multiple elements.

** Add list elements **

There are many ways to add list elements. Append is to enter only one value The other way is to add the list to the list.

Variable.append (element)

Variable + = List Variable .extend (list) List + List

a = [1,2,3]
#Add element append
a.append(4)
print(a)

[1, 2, 3, 4]

a = [1,2,3]
#Add element+=
a += a
print(a)

[1, 2, 3, 1, 2, 3]

a = [1,2,3]

#Add element extend
a.extend([4,5])
print(a)

[1, 2, 3, 4, 5]

a = [1,2,3]

#Additional list of elements+list
a = a + a
print(a)

[1, 2, 3, 1, 2, 3]

List type values can contain multiple elements There are various ways to take it out.

** Change element **

How to change the element is in the place where it was extracted using index Make changes by doing assignment.

List variable [index value] = changed value

List variable [start: end] = [list] List variable [start:] = [list] List variable [: end] = [list]

a = [1,2,3,4,5]
print(a)
#Change the third element to 9
a[2] = 9
print(a)

[1, 2, 3, 4, 5] [1, 2, 9, 4, 5]

a = [1,2,3,4,5]
#Change multiple elements(From 3rd to 4th
a[2:4] = [9,8]
print(a)

a = [1,2,3,4,5]
#Change multiple elements(From second to last)
a[1:] = [7,6]
print(a)

a = [1,2,3,4,5]
#Change multiple elements(From the first to the third)
a[:3] = [8,8,8,8]
print(a)

[1, 2, 9, 8, 5] [1, 7, 6] [8, 8, 8, 8, 4, 5]

If you use the start and end of the index, multiple elements will be replaced at the same time. The order will also be affected. Let's watch out.

** Delete element **

There are also several ways to remove an element from the list.

*** How to use del and index ***

del list [index value] del list [start: end]

l = ["A", "B", "C", "D", "E", "F", "G"]
print (l)

#Delete the second
del l[1]
print (l)

#Second more,Delete the third
del l[1:3]
print (l)

['A', 'B', 'C', 'D', 'E', 'F', 'G'] ['A', 'C', 'D', 'E', 'F', 'G'] ['A', 'E', 'F', 'G']

1 element when there is only one index value If you specify more than one for start and end, multiple elements will be deleted.

*** Delete using pop function ***

List.pop (index value)

When using the pop function, be careful as an error will occur if there is no element.

l = ["A", "B", "C", "D", "E", "F", "G"]
print (l)

#Remove 4th
l.pop(3)
print (l)

['A', 'B', 'C', 'D', 'E', 'F', 'G'] ['A', 'B', 'C', 'E', 'F', 'G']

l = ["A", "B", "C", "D", "E", "F", "G"]

#If there is no element, an error will occur
l.pop(8)

IndexError : Error that occurs when the index value exceeds the number of elements

*** Remove using remove function ***

List.remove (specified value) The remove function also causes an error if the specified value is not specified.

l = ["A", "B", "C", "D", "E", "F", "G"]
print(l)

#Remove element A
l.remove('A')
print (l)

['A', 'B', 'C', 'D', 'E', 'F', 'G'] ['B', 'C', 'D', 'E', 'F', 'G']

l = ["A", "B", "C", "D", "E", "F", "G"]

#If there is no element, an error will occur
l.remove('H')

ValueError : Error caused by the list not containing the value to delete

In order to delete it with the pop and remove functions, it is necessary to devise to delete it if there is one.

** Search for list elements **

It's not a list feature You can use the ʻin` operator to find the value of an element in a list.

Value in list type

With the ʻinoperator You can search the contents and the result will be returned asbool` type.

l = ["A", "B", "C", "D", "E", "F", "G"]
print ('K' in l)

False

If you use this bool type result, you can delete it.

** Sorting list elements **

Sorting is done using the sort function. In the case of a character string, it is the character order such as ABC, and in the case of a numerical value, it is the order of the numerical value.

Ascending order: list.sort () Descending: list.sort (reverse = True)

a = [1,4,3,5,6]
print(a)

#Sort in ascending order
a.sort()
print(a)

[1, 4, 3, 5, 6] [1, 3, 4, 5, 6]

a = [1,4,3,5,6]
print(a)

#Sort in descending order
a.sort(reverse=True)
print(a)

[1, 4, 3, 5, 6] [6, 5, 4, 3, 1]

** Rearrange elements **

This is a method of rearranging the elements in the reverse order, not the size of the elements.

List.reverse ()

a = [1,4,3,5,6]
print(a)

#Sort in reverse order of storage
a.reverse()
print(a)

[1, 4, 3, 5, 6] [6, 5, 3, 4, 1]

Since the list can have multiple values It is used in programs for various purposes.

I think that the frequency of use will be about Top 3 Let's hold down how to handle it.

Tuple

I'm sorry if it doesn't appear

There is a tuple type as data similar to a list. Tuples are data types that cannot be added or changed once defined.

In python, it can be defined with () parentheses.

(Element)

The big difference from the list is that you can't add or change values.

Once you create a variable, you can change or add elements inside that variable Think of it as a list that cannot be deleted.

So, store things that will not change as a purpose It will be used like this.

#Define a tuple with 5 elements
a = (1,2,3,4,5)
print(a)

(1, 2, 3, 4, 5)

#Tuples without elements can be defined, but it doesn't make sense
b=()
print(b)

()

Same as list for element retrieval You can also use the index and slice functions.

#Take out the third element of the tuple
a = (1,2,3,4,5)
print(a[2])

3

#Tuple 2-Extract the 4th element
a = (1,2,3,4,5)
print(a[1:4])

(2, 3, 4)

You cannot add, remove, or change elements. An error will occur.

#Add tuple elements
c = (1,3,5,7,9)
c.append(11)

AttributeError: 'tuple' object has no attribute 'append'

#Delete tuples
d = (1,3,5,7,9)
del d[2]

TypeError: 'tuple' object doesn't support item deletion

#Modifying tuple elements
e =(2,3,4,5,6)
e[3]=13

TypeError: 'tuple' object does not support item assignment

If you try to modify an element of a defined tuple, you will get an error.

However, combine tuples and tuples to make another tuple You can do things like add elements.

t1 = (1,2,3,4,5)
t2 = (2,3,4,5,6)
t3 = t1 + t2
print(t3)

(1, 2, 3, 4, 5, 2, 3, 4, 5, 6)

in this way If you use it so that the elements do not change once you make it Tuples that you don't have to worry about accidentally rewriting are suitable.

There is also data in the form of tuples. I hope you can hold it down.

Dictionary type

I'm sorry if it doesn't appear

Like the list, the most used data form in python is It is a data structure called dictionary type.

The dictionary type is a key and` value paired You can manage multiple elements.

The key can be set with character as well as integer. Various types of values can be used. Also, unlike the list, the order doesn't really matter.

** Creating dictionary type **

Dictionary type can be defined with {} wave parentheses You can store key and value as elements.

{Key: Value}

#An example of a dictionary with numeric keys
d1 = {1:10,2:20}
print(d1)

{1: 10, 2: 20}

#An example of a dictionary type where the key is a string
d2 = {'a':10,'b':20}
print(d2)

{'b': 20, 'a': 10}

** Refer to dictionary elements **

You can return a value with the variable name [key].

However, without the key, you will get a error.

#Register 5 elements
sample_dic_data = {'apple': 100, 'banana': 100, 
'orange': 300, 'mango': 400, 'melon': 500}

#Key returns melon element
print(sample_dic_data['melon'])

500

sample_dic_data = {'apple': 100, 'banana': 100, 
'orange': 300, 'mango': 400, 'melon': 500}

#Key returns an element of grape
print(sample_dic_data['grape'])

KeyError: 'grape'

If the key is not in the element, a KeyError will occur. As a dictionary type function, you can add, change, and delete elements in the same way as a list.

** Add element **

Variable name [key name] = value

d3 = {1:2 , 3:4}
print(d3)

#Add dictionary elements
d3[5] = 8
print(d3)

{1: 2, 3: 4} {1: 2, 3: 4, 5: 8}

If you specify a key that already exists, the value will be overwritten and changed.

d4 = {1:2 , 3:4}
print(d4)

#Change dictionary elements
d4[1] = 18
print(d4)

{1: 2, 3: 4} {1: 18, 3: 4}

** Key search **

Using ʻin` as in the list

Key in dictionary

Then, if the key exists, False will be returned if it is not True.

d5 = {3:4 , 5:6 , 7:8}

#Search by key name
print( 7 in d5)
print( 11 in d5)

True False

mydict = {'pen':1 , 'pineapple':2 , 'apple':3}
print('apple' in mydict)

True

If the key is set as a string, the key when searching is also a string. If you set the key with the integer value, you will also be searching with the integer value when searching. Be careful about the shape of the data when searching for the key.

** Delete dictionary elements **

*** Delete all elements *** Dictionary variable name.clear ()

*** Delete by specifying an element *** del dictionary variable name [key] Dictionary variable name.pop (key)

del does not return the erased value, but pop returns the value.

d6 = {'pen':1 , 'pineapple':2 , 'apple':3}
print(d6)

#Delete with key
del d6['pen']
print(d6)

#Delete all elements
d6.clear()
print(d6)

{'apple': 3, 'pineapple': 2, 'pen': 1} {'apple': 3, 'pineapple': 2} {}

d7 = {'pen':1 , 'pineapple':2 , 'apple':3}
print(d7)

#Delete with key with pop function
print(d7.pop('pen'))
print(d7)

{'apple': 3, 'pineapple': 2, 'pen': 1} 1 {'apple': 3, 'pineapple': 2}

pop is used to do something with the erased value.

d8 = {'pen':1 , 'pineapple':2 , 'apple':3}
print(d8)

#Delete with a key that does not exist in the pop function
print(d8.pop('penpen'))

KeyError: 'penpen'

As with value references, deleting a key that does not exist will result in an error.

If you don't have the key but want to safely erase it, add a second argument to pop.

Dictionary variable name.pop (key name, value to be returned)

d9 = {'pen':1 , 'pineapple':2 , 'apple':3}
print(d9)

#Delete with a key that does not exist in the pop function
print(d9.pop('penpen' , None))

{'apple': 3, 'pineapple': 2, 'pen': 1} None

This way, if there is an element with this key, its value will be changed. If there is no element, you can make it return the value of the second argument.

If you set None, nothing seems to happen. It can be safely erased.

Using the IF statement and search function that will appear in later lectures If you have a key, you can also put in a process You can erase it well.

If you want to do something with this erased value, just a little Be careful as you will need some technique.

** See all elements **

Since the dictionary type stores multiple data There is a way to refer to all the elements.

Since the dictionary type element is composed of key and value, there are the following three reference methods.

Dictionary variable .keys (): Returns a list of keys. Dictionary variable .values (): Returns a list of values. Dictionary variable .items (): Returns a list of keys and values.

#Define a dictionary
mydict = {"pen":1, "pineapple":2, "apple":3}

#Returns a list of keys.
print(mydict.keys())

#Returns a list of values.
print(mydict.values())

#Returns a list of keys and values.
print(mydict.items())

dict_keys(['apple', 'pineapple', 'pen']) dict_values([3, 2, 1]) dict_items([('apple', 3), ('pineapple', 2), ('pen', 1)])

It's a little confusing You can get the data converted from dictionary type to list type.

Returning a list ofkeys and valuesin ʻitems () A collection ofkeys and values in tuple type What is stored as an element of thelist` is returned.

Since the contents of the returned list type are the values of the tuple type Extract the key and value from it.

How to refer to all of this I would like to go into detail in the repeated for statement. First, let's learn how to handle dictionary type.

I think the dictionary will be the most used data type in python. I think it's a good idea to try it repeatedly.

Summary

List type and dictionary type are in the TOP3 among Python languages This is a frequently used data type.

Moreover, the methods for handling are complicated and diverse.

It ’s a very important part, so how to define the data Please be sure to know the extraction method.

There are a lot of things in the control statement of the matter, so Let's remember this opportunity.

72 days until you become an engineer

Author information

Otsu py's HP: http://www.otupy.net/

Youtube: https://www.youtube.com/channel/UCaT7xpeq8n1G_HcJKKSOXMw

Twitter: https://twitter.com/otupython

Recommended Posts

You will be an engineer in 100 days --Day 33 --Python --Basics of the Python language 8
You will be an engineer in 100 days --Day 26 --Python --Basics of the Python language 3
You will be an engineer in 100 days --Day 28 --Python --Basics of the Python language 4
You will be an engineer in 100 days ――Day 24 ―― Python ―― Basics of Python language 1
You will be an engineer in 100 days ――Day 30 ―― Python ―― Basics of Python language 6
You will be an engineer in 100 days ――Day 25 ―― Python ―― Basics of Python language 2
You will be an engineer in 100 days --Day 27 --Python --Python Exercise 1
You will be an engineer in 100 days --Day 34 --Python --Python Exercise 3
You will be an engineer in 100 days --Day 31 --Python --Python Exercise 2
You will be an engineer in 100 days --Day 63 --Programming --Probability 1
You will be an engineer in 100 days --Day 65 --Programming --Probability 3
You will be an engineer in 100 days --Day 64 --Programming --Probability 2
You will be an engineer in 100 days --Day 35 --Python --What you can do with Python
You will be an engineer in 100 days --Day 86 --Database --About Hadoop
You will be an engineer in 100 days ――Day 71 ――Programming ――About scraping 2
You will be an engineer in 100 days ――Day 61 ――Programming ――About exploration
You will be an engineer in 100 days ――Day 74 ――Programming ――About scraping 5
You will be an engineer in 100 days ――Day 73 ――Programming ――About scraping 4
You will be an engineer in 100 days ――Day 75 ――Programming ――About scraping 6
You will be an engineer in 100 days --Day 68 --Programming --About TF-IDF
You will be an engineer in 100 days ――Day 70 ――Programming ――About scraping
You will be an engineer in 100 days ――Day 81 ――Programming ――About machine learning 6
You will be an engineer in 100 days ――Day 82 ――Programming ――About machine learning 7
You will be an engineer in 100 days ――Day 79 ――Programming ――About machine learning 4
You will be an engineer in 100 days ――Day 80 ――Programming ――About machine learning 5
You will be an engineer in 100 days ――Day 78 ――Programming ――About machine learning 3
You will be an engineer in 100 days ――Day 84 ――Programming ――About machine learning 9
You will be an engineer in 100 days ――Day 83 ――Programming ――About machine learning 8
You will be an engineer in 100 days ――Day 77 ――Programming ――About machine learning 2
You will be an engineer in 100 days ――Day 85 ――Programming ――About machine learning 10
You will be an engineer in 100 days ――Day 60 ――Programming ――About data structure and sorting algorithm
You become an engineer in 100 days ――Day 66 ――Programming ――About natural language processing
The basics of running NoxPlayer in Python
You become an engineer in 100 days ――Day 67 ――Programming ――About morphological analysis
How much do you know the basics of Python?
Review of the basics of Python (FizzBuzz)
About the basics list of Python basics
Learn the basics of Python ① Beginners
Will the day come when Python can have an except expression?
For Python beginners. You may be confused if you don't know the general term of the programming language Collection.
[Fundamental Information Technology Engineer Examination] I wrote an algorithm for the maximum value of an array in Python.
If you want a singleton in python, think of the module as a singleton
The story of an error in PyOCR
The story of making Python an exe
Python Note: When you want to know the attributes of an object
Become an AI engineer soon! Comprehensive learning of Python / AI / machine learning / deep learning / statistical analysis in a few days!
I didn't know the basics of Python
The result of installing python in Anaconda
Open an Excel file in Python and color the map of Japan
In search of the fastest FizzBuzz in Python
Get a datetime instance at any time of the day in Python
An example of the answer to the reference question of the study session. In python.
[Python3] Understand the basics of file operations
An engineer who has noticed the emo of cryptography is trying to implement it in Python and defeat it
[Python3] Code that can be used when you want to change the extension of an image at once
If you add sudo on ubuntu, it will be called the default python.
[Fundamental Information Technology Engineer Examination] I wrote the algorithm of Euclidean algorithm in Python.
You can call the method of the class directly in Python3 without adding @staticmethod
If you write the View decorator in urls.py in Django, the list will be higher.
If an exception occurs in the function, it will be transmitted to the caller 2
If an exception occurs in the function, it will be transmitted to the caller 1