Python 집합 대 목록 – 실제 차이점

Python 프로그래밍의 세계에서 다양한 용도로 사용되는 다양한 데이터 구조를 자주 접하게 됩니다. 이러한 구조 중에서 집합 및 목록은 일반적으로 데이터 모음을 저장하고 조작하는 데 사용됩니다.

비슷해 보일 수 있지만 속성과 사용 사례에는 눈에 띄는 차이점이 있습니다.

Python 집합 대 목록 – 실제 차이점

목차

Python 집합 및 목록 이해

좋아, 그럼 먼저 설명하자.

파이썬 세트란 무엇입니까?

Python 집합은 멤버라고 하는 고유한 요소의 정렬되지 않은 컬렉션 나타내는 내장 데이터 구조입니다.

이 강력한 도구는 특히 데이터 과학 애플리케이션 및 수학 연산에 유용합니다.

Python 집합에는 다음 속성이 있습니다.

  1. 순서가 없습니다. 즉, 집합의 요소가 인덱스와 독립적으로 저장됩니다. 이 정렬되지 않은 고유 값 모음은 효율적인 멤버십 테스트 및 집합 내포를 지원합니다.

  2. 중복 값을 허용하지 않습니다. 따라서 고유한 값으로 작업하거나, 목록에서 중복 항목을 제거하거나, 합집합, 교집합 및 대칭 차이와 같은 집합 작업을 수행해야 할 때 유용합니다.

Python에서 집합을 만드는 방법에는 두 가지가 있습니다.

  1. 중괄호라고도 하는 중괄호({})를 사용합니다.

  2. 세트에 포함하려는 요소를 포함하는 반복 가능한 단일 인수를 취하는 내장 set() 함수를 사용합니다.

중괄호와 내장 set 함수를 사용하여 Python 집합을 생성하기 위한 일반 구문은 다음과 같습니다.

my_set = {1, 2, 3}
another_set = set([4, 5, 6])

파이썬 리스트란?

Python 목록은 다른 프로그래밍 언어의 동적 배열과 유사한 내장 데이터 구조입니다.

단일 변수에 여러 항목을 저장하는 데 사용되므로 문자열, 숫자 및 부울과 같은 다양한 데이터 유형을 처리하기 위한 다목적 옵션이 됩니다.

Python 목록에는 다음과 같은 속성이 있습니다.

  1. 즉, 특정 요소가 목록에서 고유한 위치를 가지며 해당 인덱스를 통해 액세스할 수 있음을 의미합니다. 이 정렬된 컬렉션은 임의 액세스를 지원하므로 슬라이싱, 연결 및 목록 이해와 같은 작업을 수행할 수 있습니다.

  2. 변경 가능하며 목록을 만든 후 해당 요소를 변경할 수 있으므로 데이터 구조로 작업할 때 유연성을 제공합니다.

  3. Python 목록은 중복 값을 허용하고 문자열, 숫자 및 부울을 포함한 데이터 유형의 혼합을 저장할 수 있습니다.

Python에서 목록을 만드는 방법에는 두 가지가 있습니다 .

  1. 목록의 경계를 나타내는 대괄호를 사용합니다.

  2. 목록에 포함하려는 요소를 포함하는 단일 인수 또는 이터러블을 사용할 수 있는 내장 list() 함수를 사용합니다.

다음 Python 코드는 대괄호와 내장 list() 함수를 사용하여 Python 목록을 만드는 방법을 보여줍니다.

list1 = [1, 2, 3] 
list2 = list([4, 5, 6])

집합과 목록의 3가지 주요 차이점

Python 집합과 목록 간의 여러 차이점입니다. 중요한 것 중 일부는 다음과 같습니다.

1. 주문 및 인덱싱

Python 목록 의 순서 및 인덱싱 : Python 목록은 인덱싱을 지원할 수 있습니다. 즉, 목록의 위치를 ​​사용하여 목록의 요소에 액세스할 수 있습니다. 이는 알려진 순서로 데이터를 조작할 때 유연성을 제공합니다.

다음 Python 코드는 목록의 순서와 인덱싱을 보여줍니다.

# Creating a Python list
my_list = [3, 5, 2, 8, 1]

# Accessing elements using their index
first_element = my_list[0]  # This will be 3
third_element = my_list[2]  # This will be 2

# Modifying elements using their index
my_list[1] = 7  # The list becomes [3, 7, 2, 8, 1]

# Iterating over a list maintaining the order
for item in my_list:
    print(item)

Python 집합 대 목록 – 실제 차이점

Python 세트: Python 세트는 인덱싱이 없는 정렬되지 않은 컬렉션입니다. 즉, 해당 위치를 사용하여 요소에 액세스할 수 없습니다. 이는 요소의 순서가 중요하지 않을 때 유용합니다.

다음 Python 코드는 주문 및 인덱싱 세트를 보여줍니다.

# Creating a Python set
my_set = {3, 5, 2, 8, 1}

# Sets are unordered, so you cannot access elements using their position
# This would raise an error: first_element = my_set[0]

# Modifying a set by adding or removing elements
my_set.add(6)       # The set becomes {1, 2, 3, 5, 6, 8}
my_set.discard(5)   # The set becomes {1, 2, 3, 6, 8}

# Iterating over a set (order is not guaranteed)
for item in my_set:
    print(item)

Python 집합 대 목록 – 실제 차이점

2. 가변성

Python 목록: Python 목록은 변경할 수 있으므로 해당 요소를 수정할 수 있습니다. 중첩된 목록을 포함하여 모든 유형의 개체를 보유할 수 있으므로 저장할 수 있는 콘텐츠 측면에서 더 많은 유연성을 제공합니다.

다음 코드는 Python 목록의 가변성을 보여줍니다.

# Creating a Python list
my_list = [3, 5, 2, 8, 1]

# Modifying the list by appending elements
my_list.append(4)  # The list becomes [3, 5, 2, 8, 1, 4]

# Modifying the list by removing elements
my_list.remove(2)  # The list becomes [3, 5, 8, 1, 4]

# Lists can hold any type of object, including nested lists
nested_list = [1, 2, [3, 4], 5]

Python 집합 대 목록 – 실제 차이점

Python 집합: Python의 목록 과 마찬가지로 Python 집합도 변경할 수 있으며 수정할 수 있습니다. 그러나 Python의 집합은 해시 가능한(불변) 개체만 보유할 수 있습니다. 즉, 목록과 같은 변경 가능한 개체를 포함하는 집합이나 집합을 가질 수 없습니다.

다음 코드는 Python 세트의 가변성을 보여줍니다.

# Creating a Python set
my_set = {3, 5, 2, 8, 1}

# Modifying the set by adding elements
my_set.add(6)       # The set becomes {1, 2, 3, 5, 6, 8}

# Modifying the set by removing elements
my_set.discard(5)   # The set becomes {1, 2, 3, 6, 8}

# Sets can only hold hashable (immutable) objects
valid_set = {1, 2, 3, 4, (5, 6)}

# The following would raise an error because lists are mutable and cannot be stored in sets
# invalid_set = {1, 2, [3, 4]}

Python 집합 대 목록 – 실제 차이점

요소의 고유성

Python 집합: 집합의 주요 기능은 고유한 요소만 저장한다는 것입니다. 목록에 중복 값을 추가해도 무시됩니다. 이것은 중복 제거 또는 고유 요소의 존재 확인과 같은 다양한 집합 작업에 집합 개체를 이상적으로 만듭니다.

# Creating a Python set with duplicate elements
my_set = {3, 5, 2, 8, 1, 3, 2, 5}
# The duplicate elements are automatically removed: {1, 2, 3, 5, 8}

# Checking for the presence of a unique element
if 5 in my_set:
    print("5 is in the set")
# Output: 5 is in the set

# Removing duplicates from a list using a set
my_list = [3, 5, 2, 8, 1, 3, 2, 5]
unique_list = list(set(my_list))
# The unique_list becomes [1, 2, 3, 5, 8]
  • Python 집합 대 목록 – 실제 차이점

    Python 목록: 목록은 중복 값을 허용하고 순서를 유지합니다. 이는 중복 및 요소 순서가 중요한 역할을 하는 사용 사례에서 필수적일 수 있습니다.

    # Creating a Python list with duplicate elements
    my_list = [3, 5, 2, 8, 1, 3, 2, 5]
    # The list contains duplicate values: [3, 5, 2, 8, 1, 3, 2, 5]
    
    # Checking for the presence of an element in a list
    if 5 in my_list:
        print("5 is in the list")
    # Output: 5 is in the list
    
    # Counting the occurrences of a value in a list
    count_of_5 = my_list.count(5)
    print("5 appears", count_of_5, "times")
    # Output: 5 appears 2 times

    Python 집합 대 목록 – 실제 차이점

3. 지원되는 작업

집합과 목록에서 수행할 수 있는 다양한 작업이 있으며 각각 특정 작업에 최적화되어 있습니다.

Python Lists: Due to their ordered and index-based nature, lists support operations like slicing, concatenation, repetition, and list comprehension. They also provide built-in methods, such as append(), pop(), and sort(), that allow you to manipulate elements of a list.

# Creating a Python list
my_list = [3, 5, 2, 8, 1]

# Slicing a list
sub_list = my_list[1:4]  # The sub_list becomes [5, 2, 8]

# Concatenation of two lists
list1 = [1, 2, 3]
list2 = [4, 5, 6]
concatenated_list = list1 + list2  # The concatenated_list becomes [1, 2, 3, 4, 5, 6]

# Repetition of a list
repeated_list = list1 * 2  # The repeated_list becomes [1, 2, 3, 1, 2, 3]

# List comprehension
squared_list = [x ** 2 for x in my_list]  # The squared_list becomes [9, 25, 4, 64, 1]

# Using built-in methods
my_list.append(4)  # The list becomes [3, 5, 2, 8, 1, 4]
my_list.pop()      # The list becomes [3, 5, 2, 8, 1]
my_list.sort()     # The list becomes [1, 2, 3, 5, 8]

Python 집합 대 목록 – 실제 차이점

Python Sets: Sets are optimized for performing set-related operations like union, intersection, difference, and checking membership using hash functions to find elements quickly. Since they are unordered and lack indexing, set operations differ from list-based ones.

# Creating Python sets
set1 = {1, 2, 3, 4, 5}
set2 = {4, 5, 6, 7, 8}

# Union operation
union_set = set1.union(set2)  # The union_set becomes {1, 2, 3, 4, 5, 6, 7, 8}

# Intersection operation
intersection_set = set1.intersection(set2)  # The intersection_set becomes {4, 5}

# Difference operation
difference_set = set1.difference(set2)  # The difference_set becomes {1, 2, 3}

# Checking membership
if 3 in set1:
    print("3 is a member of set1")
# Output: 3 is a member of set1

Python 집합 대 목록 – 실제 차이점

How Do You Choose The Right Data Structure?

When working with Python, it’s essential to select the most suitable data structure for your specific task. In this section, we will discuss the best scenarios for using sets and lists, along with their unique advantages.

Let’s get into it.

Use Cases for Sets

Sets offer several advantages that make them the ideal choice for certain tasks:

Uniqueness: If you need to store a collection of unique elements, sets are the way to go. Sets automatically eliminate duplicates, ensuring that each element in the set is distinct.

Membership tests: Sets provide faster membership tests compared to lists. Due to their underlying hash table implementation and the use of hash functions, sets allow for highly efficient lookups based on hash values.

Set operations: Sets support operations such as union, intersection, difference, and symmetric difference that can be useful in many algorithms, data processing tasks, and data science applications.

Use Cases for Lists

Lists are better suited for the following scenarios:

Ordered data: Lists maintain the order of elements, making them suitable for tasks that require respecting the sequence of items, such as processing data in the order it was created or when support indexing is needed.

Mutable data: Lists are mutable, allowing you to add, remove, or modify a specific element as needed. This flexibility makes lists suitable for tasks that involve changing the content of the collection or when working with nested data structures, such as lists of lists or dictionaries.

Non-unique elements: Unlike sets, lists can store duplicate elements, making them appropriate for situations where the frequency of items matters, such as counting occurrences or maintaining the order of duplicate values.

Check out the below to show to further your learning.

APerformance Comparison Between Sets and Lists

In this section, we will compare the performance of Python sets and lists in terms of time complexity and memory usage, which is essential when working with large data structures or when optimizing code for efficiency.

Time Complexity

When it comes to time complexity, sets and lists have different strengths and weaknesses depending on the operations you perform due to their underlying implementation.

  1. Searching: Sets use hash lookups and hash functions, which makes searching for an item significantly faster compared to lists. For example, searching through 100,000 items takes 49.663 seconds with a list, but only 0.007 seconds with a set, as it takes advantage of the hash value for quick access.

  2. 반복: 목록은 항목을 반복할 때 집합보다 약간 빠릅니다. 세트는 고유성을 보장하기 위해 추가 작업이 필요하지만 목록은 직접 인덱싱을 사용하여 단순하게 정렬된 컬렉션을 유지하기 때문입니다.

메모리 사용량

집합은 항목의 고유성을 보장하기 위해 해시 테이블을 유지 관리해야 하기 때문에 일반적으로 목록보다 더 많은 메모리를 사용하며 이로 인해 메모리 소비가 증가합니다.

목록은 요소를 순차적으로만 저장하므로 메모리 소비가 낮아져 대량의 데이터 컬렉션을 처리할 때 메모리 효율성이 높아집니다.

import time
import random

# Generating a large list and set with 100,000 random integers
large_list = [random.randint(1, 1_000_000) for _ in range(100_000)]
large_set = set(large_list)

# Searching for an item in the list and set
search_value = random.randint(1, 1_000_000)

# Measuring the time it takes to search for the item in the list
start_time = time.time()
result = search_value in large_list
end_time = time.time()
list_search_time = end_time - start_time
print(f"List search time: {list_search_time:.6f} seconds")

# Measuring the time it takes to search for the item in the set
start_time = time.time()
result = search_value in large_set
end_time = time.time()
set_search_time = end_time - start_time
print(f"Set search time: {set_search_time:.6f} seconds")

# Iterating over the list and set
# Measuring the time it takes to iterate over the list
start_time = time.time()
for item in large_list:
    pass
end_time = time.time()
list_iter_time = end_time - start_time
print(f"List iteration time: {list_iter_time:.6f} seconds")

# Measuring the time it takes to iterate over the set
start_time = time.time()
for item in large_set:
    pass
end_time = time.time()
set_iter_time = end_time - start_time
print(f"Set iteration time: {set_iter_time:.6f} seconds")

제공된 코드는 검색 및 반복을 위한 시간 복잡도 측면에서 Python 집합과 목록 간의 성능 비교를 보여줍니다.

중괄호(중괄호라고도 함)로 묶인 큰 목록과 임의의 정수 집합을 생성합니다.

그런 다음 목록과 집합 모두에서 단일 인수를 사용하여 특정 항목을 검색하는 데 걸리는 시간을 측정하고 목록과 집합의 모든 요소를 ​​반복하는 데 걸리는 시간을 측정합니다.

Python 집합 대 목록 – 실제 차이점

출력은 기본 구현에서 비롯된 검색 및 반복에 대한 Python 목록과 세트 간의 성능 차이를 보여줍니다.

효율적인 조회를 위해 해시 함수를 사용하여 해시 값을 계산하기 때문에 검색 작업은 목록(0.002999초)보다 세트(0.000000초)에서 더 빠릅니다. 그러나 목록(0.007995초)을 반복하는 것은 집합(0.017989초)을 반복하는 것보다 약간 더 빠릅니다. 왜냐하면 세트는 고유성을 보장하기 위해 추가 작업이 필요하기 때문입니다.

일반적인 작업 및 방법

Python의 집합과 목록에는 각각 특정 작업 및 데이터 조작에 최적화된 다양한 작업과 메서드가 있습니다. 이러한 방법 중 일부는 다음과 같습니다.

방법 설정

집합 메서드는 수학적 연산과 유사한 작업을 수행하며 컬렉션의 고유한 값을 처리하기 위한 강력한 도구입니다.

  • add(요소): 아직 존재하지 않는 경우 세트에 요소를 추가합니다.

  • remove(element): 세트에서 지정된 요소를 제거합니다. 요소를 찾을 수 없으면 오류가 발생합니다.

  • 폐기(요소): 지정된 요소가 있는 경우 집합에서 해당 요소를 제거합니다. 요소를 찾을 수 없는 경우 오류가 발생하지 않습니다.

  • union(set2): 원래 집합과 set2의 모든 요소를 ​​포함하는 새 집합을 반환하여 집합 작업을 효과적으로 수행합니다.

  • 교차(세트2): 원래 세트와 세트2 모두에 공통적인 요소를 포함하는 새 세트를 반환합니다.

  • difference(set2): set2가 아닌 원래 집합의 요소를 포함하는 새 집합을 반환합니다.

  • symmetric_difference(set2): 원본 집합 또는 집합 2 중 하나의 요소를 포함하지만 둘 다에는 포함하지 않는 새 집합을 반환합니다.

목록 방법

목록 메서드는 데이터를 조작하는 다양한 방법을 제공합니다.

  • append(요소): 목록 끝에 요소를 추가합니다.

  • extend(iterable): iterable(예: 다른 목록)의 모든 요소를 ​​목록 끝에 추가합니다.

  • insert(인덱스, 요소): 지정된 인덱스에 요소를 삽입합니다.

  • remove(element): 목록에서 지정된 요소의 첫 번째 항목을 제거합니다. 요소가 없으면 오류가 발생합니다.

  • pop(index): 지정된 인덱스에서 요소를 제거하고 반환합니다. 인덱스가 제공되지 않으면 마지막 요소를 제거합니다.

  • index(요소): 목록에서 지정된 요소가 처음 나타나는 인덱스를 반환합니다.

  • count(요소): 목록에서 지정된 요소의 발생 횟수를 반환합니다.

  • sort(): 기본적으로 오름차순으로 목록을 정렬합니다. 내림차순의 경우 reverse=True 매개변수를 사용하십시오.

  • reverse(): 목록의 요소 순서를 반대로 바꿉니다.

이러한 Python 집합 및 목록 메서드를 사용하여 데이터를 효과적으로 조작하고 Python 프로그래밍, 데이터 과학 및 기타 응용 프로그램의 다양한 문제를 해결할 수 있습니다.

우리의 마지막 말

데이터 구조에 대해 Python 목록과 세트 중에서 선택할 때 순서가 지정된 항목 모음이 필요하고, 중복 요소를 보존하고, 인덱스로 요소에 액세스하는 기능이 필요한 경우 목록을 사용하는 것이 좋습니다.

요소의 고유성이 필수적이고 요소의 순서가 중요하지 않으며 빠른 멤버십 테스트가 선호되는 경우 세트를 선택하십시오. 목록은 반복에서 탁월하지만 세트는 보다 효율적인 포함 검사를 제공합니다.

선택은 궁극적으로 프로젝트의 요구 사항에 따라 달라집니다. 각 데이터 구조는 고유한 이점과 제한 사항을 제공하므로 Python 프로그래밍의 다양한 작업을 처리하기 위한 강력한 도구가 됩니다. 즐기다!

Leave a Comment

SharePoint의 계산된 열 | 개요

SharePoint의 계산된 열 | 개요

SharePoint에서 계산된 열의 중요성과 목록에서 자동 계산 및 데이터 수집을 수행하는 방법을 알아보세요.

Power Apps에서 변수 만들기: 컬렉션 작업

Power Apps에서 변수 만들기: 컬렉션 작업

컬렉션 변수를 사용하여 Power Apps에서 변수 만드는 방법 및 유용한 팁에 대해 알아보세요.

Microsoft Flow HTTP 트리거 | Power Automate 자습서

Microsoft Flow HTTP 트리거 | Power Automate 자습서

Microsoft Flow HTTP 트리거가 수행할 수 있는 작업과 Microsoft Power Automate의 예를 사용하여 이를 사용하는 방법을 알아보고 이해하십시오!

Power Automate 흐름: 사용법 및 유형 설명

Power Automate 흐름: 사용법 및 유형 설명

Power Automate 흐름 및 용도에 대해 자세히 알아보세요. 다양한 작업 및 시나리오에 사용할 수 있는 다양한 유형의 흐름에 대해 설명합니다.

흐름에서 Power Automate 종료 작업 제어

흐름에서 Power Automate 종료 작업 제어

조건이 충족되지 않는 경우 흐름에서 작업을 종료하는 Power Automate 종료 작업 컨트롤을 올바르게 사용하는 방법을 알아봅니다.

PowerApps 시작 기능: 앱에서 다른 서비스를 시작하는 방법

PowerApps 시작 기능: 앱에서 다른 서비스를 시작하는 방법

PowerApps 실행 기능에 대해 자세히 알아보고 자신의 앱에서 바로 웹사이트, 전화, 이메일 및 기타 앱과 같은 기타 서비스를 실행하십시오.

Power Automate의 HTTP 요청 – 소개

Power Automate의 HTTP 요청 – 소개

타사 애플리케이션 통합과 관련하여 Power Automate의 HTTP 요청이 작동하는 방식을 배우고 이해합니다.

Power Automate Desktop: 마우스 클릭 보내기 기능을 사용하는 방법

Power Automate Desktop: 마우스 클릭 보내기 기능을 사용하는 방법

Power Automate Desktop에서 Send Mouse Click을 사용하는 방법을 알아보고 이것이 어떤 이점을 제공하고 흐름 성능을 개선하는지 알아보십시오.

PowerApps 변수: 컨텍스트 및 전역 변수 식별

PowerApps 변수: 컨텍스트 및 전역 변수 식별

PowerApps 변수의 작동 방식, 다양한 종류, 각 변수가 앱에 기여할 수 있는 사항을 알아보세요.

Power Automate에서 실행할 데스크톱 흐름 예약

Power Automate에서 실행할 데스크톱 흐름 예약

이 자습서에서는 Power Automate를 사용하여 웹 또는 데스크톱에서 작업을 자동화하는 방법을 알려줍니다. 데스크톱 흐름 예약에 대한 포괄적인 가이드를 제공합니다.