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

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 프로그래밍의 다양한 작업을 처리하기 위한 강력한 도구가 됩니다. 즐기다!


파이썬에서 자기란 무엇인가: 실제 사례

파이썬에서 자기란 무엇인가: 실제 사례

파이썬에서 자기란 무엇인가: 실제 사례

R에서 RDS 파일을 저장하고 로드하는 방법

R에서 RDS 파일을 저장하고 로드하는 방법

R의 .rds 파일에서 개체를 저장하고 로드하는 방법을 배웁니다. 이 블로그에서는 R에서 LuckyTemplates로 개체를 가져오는 방법도 다룹니다.

첫 N 영업일 재방문 – DAX 코딩 언어 솔루션

첫 N 영업일 재방문 – DAX 코딩 언어 솔루션

이 DAX 코딩 언어 자습서에서는 GENERATE 함수를 사용하는 방법과 측정값 제목을 동적으로 변경하는 방법을 알아봅니다.

LuckyTemplates에서 다중 스레드 동적 시각적 개체 기술을 사용한 인사이트 쇼케이스

LuckyTemplates에서 다중 스레드 동적 시각적 개체 기술을 사용한 인사이트 쇼케이스

이 자습서에서는 다중 스레드 동적 시각적 개체 기술을 사용하여 보고서의 동적 데이터 시각화에서 통찰력을 만드는 방법을 다룹니다.

LuckyTemplates의 컨텍스트 필터링 소개

LuckyTemplates의 컨텍스트 필터링 소개

이 기사에서는 필터 컨텍스트를 살펴보겠습니다. 필터 컨텍스트는 모든 LuckyTemplates 사용자가 처음에 배워야 하는 주요 주제 중 하나입니다.

LuckyTemplates 온라인 서비스에서 앱을 사용하기 위한 최고의 팁

LuckyTemplates 온라인 서비스에서 앱을 사용하기 위한 최고의 팁

LuckyTemplates Apps 온라인 서비스가 다양한 소스에서 생성된 다양한 보고서 및 인사이트를 관리하는 데 어떻게 도움이 되는지 보여주고 싶습니다.

시간 경과에 따른 이익 마진 변화 분석 - LuckyTemplates 및 DAX를 사용한 분석

시간 경과에 따른 이익 마진 변화 분석 - LuckyTemplates 및 DAX를 사용한 분석

LuckyTemplates에서 측정 분기 및 DAX 수식 결합과 같은 기술을 사용하여 수익 마진 변경을 해결하는 방법을 알아봅니다.

DAX Studio의 데이터 캐시에 대한 구체화 아이디어

DAX Studio의 데이터 캐시에 대한 구체화 아이디어

이 자습서에서는 데이터 캐시의 구체화 아이디어와 결과 제공 시 DAX 성능에 미치는 영향에 대해 설명합니다.

LuckyTemplates를 사용한 비즈니스 보고

LuckyTemplates를 사용한 비즈니스 보고

지금까지 Excel을 계속 사용하고 있다면 지금이 비즈니스 보고 요구 사항에 LuckyTemplates를 사용하기 시작하는 가장 좋은 시기입니다.

LuckyTemplates 게이트웨이란? 당신이 알아야 할 모든 것

LuckyTemplates 게이트웨이란? 당신이 알아야 할 모든 것

LuckyTemplates 게이트웨이란? 당신이 알아야 할 모든 것