WeSeong Log in
← Back to posts
Programming language

Python lists, tuples, dictionaries, and functions

Python lists, tuples, dictionaries, and functions

I. Overview

Python CollectionsNotable examples include: List, Tuple, DictionaryThere are several data structures available in Python. A list is a collection of data items arranged in a specific order. Lists can hold any type of data. Tuples are similar to lists, but they are immutable, meaning their contents cannot be changed after they are created. Dictionaries are collections of data items that are organized into key-value pairs. Python provides several useful functions for lists, tuples, and dictionaries, such as adding, deleting, modifying, and finding elements. These functions work like magic, allowing you to easily manipulate your data. FunctionIt can have parameters and return a value. It utilizes the concepts of local and global variables, where local variables only affect the function in which they are defined, while global variables can be accessed by multiple functions.


Built-in



II. Python Lists

In Python ListIn order to understand Stack, Queue, DequeueIt's important to understand these concepts. While it might take some practice to fully grasp them, you'll quickly become familiar with them after using them a few times. Since these concepts are fundamental, I'll provide a brief explanation here. However, there are many other blog posts and articles that offer more detailed explanations, so I highly recommend checking them out.


The stack is Latecomer's advantageLast-In, First-Out (LIFO) When data arrives through a structure, it is placed on top. When retrieving or using the data, the data that was most recently added is processed first. The queue is First-In, First-Out (FIFO)Unlike a stack, which follows a Last-In, First-Out (LIFO) principle, a queue operates on a First-In, First-Out (FIFO) principle. This means that the first data item entered is the first one to be removed. This design addresses the limitations of linear queues by ensuring that data is processed in the order it was received. The data can be added and removed regardless of the order. You have the option to either remove the first data entry or the last data entry.


In Python, a list can group multiple pieces of data together, regardless of the data type. As a simple example from everyday life, consider a class in school. The class itself can be seen as a container that holds multiple students, while each student represents individual data. In this analogy, the list represents the class, and the students represent the individual data. IndexThis allows for the creation of a list of data, similar to how students have unique student IDs. Each entry in the list is assigned a number, indicating its position within the list.


※ It's important to note that the index numbers start from 0, not 1. This is related to the fact that computers operate programs using a binary system based on 0 and 1.


When creating a list

list = []
list = [1, 2, 3, 4]

This can be generated in this format. The first example shows an empty list, as no data has been entered yet. The second example shows a list containing four numbers: 1, 2, 3, 4. In this case, the first data index is 0, and the corresponding value is 1. The second data index is 1, and the corresponding value is 2. ··· In this way, each index number and data are matched. Lists can take on various forms.

Programming languages and Python (variables, operators, data types)

As you can see in the previous post, the basic data types – integers, floats, strings, and booleans – can all be represented as lists.


※ One of Python's unique features is that, in addition to basic data types, Whether it's a list or tuples/dictionaries learned later, they can also be treated as a single data item within a list.You can join us!


Instead of categorizing data types, we can create a single list for all data. There are two ways to access the data in this list: either by directly calling the data using its index number, or by using a loop.

list = [1, 2, 3, 4]
print(list[0])
결과 출력 ==> 1

for i in list :
    print(i, "", end="")
결과 출력 ==> 1 2 3 4

※ And here, another unique feature of Python Adding and multiplying in the list.This allows you to either combine two lists or multiply one list by a specific number, creating a new list with repeated data.

list1 = [1, 2, 3]
list2 = [4, 5, 6]
print(list1 + list2)
결과 출력 ==> [1, 2, 3, 4, 5, 6]

print(list1 * 2)
결과 출력 ==> [1, 2, 3, 1, 2, 3]


The data in the list ChangesThis is also possible when using the index number.

list = ['a', 'b', 'c']
list[1] = 'd'
print(list)
결과 출력 ==> ['a', 'd', 'c']

list[2:3] = ['e', 'f']
print(list)
결과 출력 ==> ['a', 'd', 'e', 'f']

Python uniquely allows you to specify a range of indices instead of just a single index number. In the example above, the number before the slice indicates the starting index. Initial valueAnd the following number is Which data set are you referring to? It represents the range. The way the `range()` function works is similar. If you don't specify a starting value, it defaults to the first data point, and if you want to specify data in reverse order, you can use -1, -2. ··· This can be utilized.


The list includes functions for adding, deleting, modifying the number of items, sorting, reversing, and copying data.

list = [1, 2, 3]
list.append(10)
print(list)
결과 출력 ==> [1, 2, 3, 10]

list.insert(1, 20)
print(list)
결과 출력 ==> [1, 20, 2, 3, 10]

These two functions are used to add data to a list. append()In the case of adding data to the end. insert()In this case, the function receives two inputs: the first input specifies the location where the data should be placed, and the second input is the data itself.


list = [1, 2, 3, 4, 5]
del(list[0])
print(list)
결과 출력 ==> [2, 3, 4, 5]

del(list) ==> 리스트를 통째로 없앰

list = [1, 2, 3]
list.remove(2)
print(list)
결과 출력 ==> [1, 3]

list = [1, 2, 3]
list.pop()
3
print(list)
결과 출력 ==> [1, 2]

delete()Egg remove()`del()` is a function that deletes data from a list. It can either delete specific items or the entire list. `remove()` only deletes a specific item within the list. If there are multiple instances of the same data, it only deletes the first one encountered. pop() In the case of a function, it returns the last data item in the list and then deletes it.


count() The function is simple: you provide the data you want to search for, and it tells you how many items match. List.count(the value to search for)You can use this.


list = [1, 4, 2, 5, 3]
list.sort()
print(list)
결과 출력 ==> [1, 2, 3, 4, 5]

When you want to sort a list that is not currently sorted in a specific order. sort() It uses a function to sort. By default, it sorts in ascending order, but if you pass `reverse=True` as an argument, it sorts in descending order.


※ In practice, while studying Sorting algorithmsYou can receive missions to implement these algorithms. While challenging, they are helpful, and there are various sorting methods, each with different sorting times, such as bubble sort and quicksort. I recommend trying to create your own algorithms using conditional statements and loops, as this can be a fun and educational experience.


list = [20, 10, 40, 50, 30]
list.reverse()
print(list)
결과 출력 ==> [30, 50, 40, 10, 20]

list = [1, 2, 3]
copyList = list.copy()
print(copyList)
결과 출력 ==> [1, 2, 3]

reverse() The function reverses the order of data elements in a list, starting from the last element. copy() The `copy()` function creates a new list that is a copy of the original list. As shown in the example above, you can store the newly created list in a new variable.


※ Important concepts to keep in mind when copying a list: Shallow CopyWow Deep CopyThere are already many good articles that introduce this concept, so I will briefly explain it. Shallow copying simply copies only the address values of the existing list, so if the newly copied list or the original list is modified, both will be affected. Deep copying, on the other hand, copies only the actual data from the existing list into a new memory space, so it is not affected by changes to the data.


If you understand the concept of a list Two-dimensional listIt's helpful to keep this in mind.

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

This is the structure of the data. To effectively use this list, nested loops are necessary. While it can be used in various ways, it is recommended to practice thoroughly as it involves complex concepts. When accessing specific data in this 2D list, you need two index numbers, and you can retrieve it like this: 'list[0][1] = 2'. To understand 2D lists... Matrices in mathematicsIt's helpful to know this. And, once you can effectively use 2D lists, "Tetris" You can also create the same game. I recommend starting with a game that has a higher difficulty level, and thoroughly studying resources like books or other blogs before attempting it!



Ⅲ. Python Tuples

TupleIt's not possible to write to this list. Reading-only listIt's straightforward to understand. The other characteristics are the same, and the functions used in the list are: delete() The function only allows deleting a single data point at a time, but it is possible to delete the entire list. Later... ConstantIt's helpful to understand this concept. "Initially, the value assigned to a variable remains constant and does not change."Think of a tuple as a constant list.

tuple1 = (1, 2, 3)
tuple2 = 1, 2, 3

tuple3 = (10,)
tuple4 = 10,

Tuples must have their data defined when they are created. This data remains constant and does not change, unlike lists which can be modified. ParenthesesIt uses [specific technology/method]. The list is: Square bracketsIt uses the following example: to create a tuple containing only one data item, add the data to the end of the data. (comma)You need to add the appropriate operator. Like lists, tuples can be accessed using index numbers, and you can perform addition and multiplication!


※ In addition, there are functions that can convert between lists and tuples. These functions can convert a list to a tuple, or a tuple to a list. If you want to convert a list to a tuple, list of tuplesWhen you want to convert something into a tuple tuple(list) You can use it this way.



Ⅳ. Python Dictionaries

DictionaryThink of it like a dictionary; each pair represents a single data entry, with one being the key and the other being the value.

dict = {'a':1, 'b':2, 'c':3}
dict = {1:'a', 2:'b', 3:'c'}

When creating a dictionary as shown in the examples above '{}' (curly braces)It uses the "key-value" data structure. The data type associated with each key can be any type. However, keys cannot be duplicated. And, unlike the list OrderThere isn't one.

dict = {1:'a', 2:'b'}
print(dict[1])
출력 결과 ==> a

The list accessed data using an index number, while the dictionary... Accessing data in kilobytesThis works. As shown in the example, by placing the key within square brackets, the corresponding value will be displayed. When adding data to a dictionary 'dict[key] = value'However, when adding elements, it's important to ensure that the key-value pairs are always added as a pair, just like in a list. If duplicate keys are entered, the previously existing value will be overwritten with the newly assigned value. delete() It can be deleted using a function.


dict = {'가수':'트와이스', '인기곡':'Cheer Up!', '데뷰':'서바이벌 식스틴'}
print(dict.keys())
결과 출력 ==> ['가수', '인기곡', '데뷰']
print(dict.values())
결과 출력 ==> ['트와이스', 'Cheer Up!', '서바이벌 식스틴']
print(dict.items())
결과 출력 ==> [('가수', '트와이스'), ('인기곡', 'Cheer Up!'), ('데뷰', '서바이벌 식스틴')]

Useful functions in the dictionary keys(), values(), items()The `keys()` function returns a list of only the keys in the dictionary. The `values()` function returns a list of only the values, and the `items()` function returns a list of key-value pairs as tuples.(It has the same structure as a two-dimensional list!)I will bring it over.


※ As used in the sentence above inThis applies not only to dictionaries, but also to conditional statements and loops. It's the opposite of "in". notThere are also operators that check for the presence or absence of data within specific data structures. The `in` operator checks if a given value exists within a list, tuple, dictionary, or range. Conversely, the `not in` operator checks if a given value is *not* present within those data structures.



V. Python Functions

[SK Secure, SeSAC, Dong-Seoul Branch 1] Programming Languages and Python (Variables, Operators, Data Types)

The function, which was briefly mentioned in the previous post, takes parameters and performs a specific action after receiving them. returnThis is a system where the value is returned. A simple example to understand is a vending machine: you insert coins, and in return, you receive a drink.

def func1() :
    동작 구조
def func2() :
    동작 구조
    return

This is how the function is defined, and it can be categorized into: When there is a value to return, and when there is not.It is located there. When a value is being returned. The value corresponding to a specific variable can be assigned and then passed as a parameter to other functions, or used for various calculations. When there is no value to return.The function terminates after the specified operation is executed, and it is a representative function that was encountered first. print() These functions are useful, such as `print()`, `len()`, and `count()`, which are built-in functions in Python. However, when you actually start coding, User-defined functionsThis results in each user having their own set of functions, leading to a very diverse range of function behaviors.


Function ParametersIt can either receive data and operate, or it can operate without receiving data. After processing and handling the data received as input, it will return the results.

def add(x, y) :
    result = 0
    result = x + y
    return result

This structure can be created as follows, as shown in the example above. "Plus"This is a function that performs a specific task.


※ If you also study functions Creating a programThis allows you to start developing the program. However, the code can become quite lengthy. I would like to share some tips on how to structure the program effectively for easier development. 1. The function definition section comes first. 2. The declaration of global variables comes next. 3. The core logic (main) code of the program follows. Global variables will be explained in detail, and comments explaining their function or what they represent will help in understanding the code. While this structure is not mandatory, it is highly recommended to practice using it, especially when dealing with hundreds or thousands of lines of code, as it can significantly complicate maintenance.


To make studying more engaging, I've set a challenge: to analyze the provided examples, considering potential exceptions and structures. As I mentioned earlier, the way a function works can vary greatly, so these examples are not definitive solutions. I hope to see better code!


Mission: Implementing a calculator using functions.


















# 더하기
def add(x,y) :
	return x + y

# 빼기
def sub(x,y) :
	return x - y

# 곱하기
def multi(x,y) :
	return x * y

# 나누기
def div(x,y) :
	return x / y

# 입력
def inputNumber() :
	num = 0
	while True :
		num = input("숫자 입력 : ")
		
		if not(num.isdigit()) :
			print("숫자를 입력해주세요.")
			continue
		else :
			break

	return int(num)

# 계산입력
def inputSign() :
	sign = ''

	while True :
		sign = input("계산 입력 ( +, -, *, / ) : ")
		
		if sign not in ('+', '-', '*', '/') :
			print("제대로 된 계산을 입력해주세요.")
		else :
			break

	return sign

def control() :
	sign = inputSign()

	x = inputNumber()
	y = inputNumber()

	mark = {"+":add(x,y), "-":sub(x,y), "*":multi(x,y), "/":div(x,y)}

	result = mark[sign]

	print(f"## 계산기 : {x} {sign} {y} = {result}")

def main() :
	while True :
		print("계산기 작동")
		exit = int(input("진행1, 종료2 : "))
		
		if exit == 2 :
			break

		control()

main()


One unique aspect of functions in Python is their handling of parameters. While the number of parameters is not specific to any particular language, Python's approach is... Default values for parametersIt is possible to designate them.

def add(x, y, z = 0) :
    result = 0
    result = x + y + z
    return result

print(add(4, 5))
결과 출력 ==> 9

If a function is originally defined with three parameters, you need to provide all three data values. However, if a variable is defined with a default value, as shown in the example above, Even with just two data points, the function operates correctly.There are a few additional points to keep in mind when working with parameters: when calling a function, "This is how the function is executed." It is crucial to accurately input data based on the number of parameters in the function. If the function's logic (structure) involves a changing number of parameters, a separate function should be created.


※ The data type for each parameter can be anything!


def func1(x, y) :
    result = x + y
    return result

def func2(x, y) :
    result1 = x + y
    result2 = x - y
    return result1, result2

sum, sub = func2()

As shown in the examples above, a Python function's key characteristic is its ability to perform a specific task. The possibility of receiving multiple data points.func1() is a basic "addition" function, while func2() receives the same data but can perform both addition and subtraction. Of course, if the function returns more than one value, the receiving variable must also be able to accommodate that many values.


def myFunc() :
    pass

if True :
    pass

There are keywords that can be used in functions or conditional statements, and are also available for use in classes that will be defined later. "pass"The meaning is to declare the classes or functions that will be implemented according to the program's design, and then define them later. While you can leave these as comments, they can also be useful when assigning roles based on the program's logic or functionality.


※ Functions also require memory space. They have an address, and when a function returns, it typically ends and is also removed from the memory space. While this may not be a concern in simple programs, it's a good idea to consider the role and behavior of functions in larger programs to avoid potential issues like memory leaks, which can lead to errors or program termination, especially when using loops or recursive functions.


The final concept to remember in this function is: Global variablesWow Local variablesIt is.

def func1() :
    a = 10
    print(a)

def func2() :
    print(a)

a = 20

func1()
func2()

As you can see in the code, both functions output the variable 'a'. However, in func1(), the variable 'a' is defined, while in func2(), it is not. In this scenario, what would be the output of variable 'a' when both functions are called and executed?

func1()
출력 결과 ==> a = 10
func2()
출력 결과 ==> a = 20

The results are as follows: the `func1()` function declares and defines a variable named `a` within its own scope, while the `func2()` function references a variable named `a` that is declared as a global variable. Variables declared and defined within a function are local variables.and several functions A common element that can be shared is the global variable.It is. So, why doesn't the func1() function refer to the global variable 'a'?


The answer is that local variables are more important than global variables. FirstThis is because functions also require memory space. As mentioned earlier, when a function is defined, memory space is allocated for it, and variables like 'a' are stored within that allocated space. Therefore, you can directly access and use your local variables. However, in the case of the `func2()` function, the variable 'a' is not present within its allocated memory space. Nevertheless, the code requires access to the variable 'a', so it searches for 'a' within the accessible scope. As a result, the global variable 'a' can be accessed and printed.


※ Keywords that allow direct reference of global variables within a function. "global"However, it is possible to reassign global variables that have been imported from other parts of the codebase.

def func1() :
    global a
    a = 10
    print(a)

def func2() :
    print(a)

a = 20

func1()
출력 결과 ==> a = 10
func2()
출력 결과 ==> a = 10

The difference from the example above is that the `func1()` function accesses global variables directly. ReallocationThe only thing that was done was to declare it as a global variable. If it hadn't been declared as global, it would have functioned as a local variable. However, because it was declared as a global variable, it was reassigned as a global variable. This is something to be careful about, as global variables can reference other functions depending on the program's functionality, which means that the data can change. Causes malfunctionsIt is possible. Therefore, when using global keywords, it is important to be mindful of this.



Review

Today, I studied lists, tuples, dictionaries, and functions. I'm gradually becoming more proficient in Python, and I'm able to write more diverse code and create various programs (like a calculator and lottery program). However, I believe these concepts can be quite challenging, especially for those who are new to them. I remember that it took me a while to get used to them, and there are many aspects that I haven't covered in this article. Therefore, if you are reading this, I would recommend that you approach it with the understanding that it will be challenging and require significant study. Please don't think that you can't do it just because it's difficult! I still feel like I'm not fully proficient, so I would appreciate it if you could consider this article as a basic introduction.