Python Set Vs List – справжня різниця

У світі програмування на Python ви часто стикаєтеся з різними структурами даних, які служать різним цілям. Серед цих структур набори та списки зазвичай використовуються для зберігання колекцій даних і керування ними.

Хоча вони можуть виглядати схожими, існують помітні відмінності в їхніх властивостях і випадках використання.

Python Set Vs List – справжня різниця

Зміст

Розуміння наборів і списків Python

Гаразд, давайте спочатку все пояснимо.

Що таке набори Python?

Набір — це вбудована структура даних, яка представляє невпорядковану колекцію окремих елементів, які називаються членами.

Цей потужний інструмент особливо корисний у додатках для обробки даних і математичних операціях.

Набори Python мають такі властивості:

  1. Вони невпорядковані, що означає, що елементи в наборі зберігаються незалежно від їх індексу. Ця невпорядкована колекція унікальних значень підтримує ефективні тести на членство та розуміння набору.

  2. Вони не допускають дублювання значень. Це робить їх корисними, коли вам потрібно працювати з унікальними значеннями, видаляти дублікати зі списку або виконувати такі операції з наборами, як об’єднання, перетини та симетричні різниці.

Є два способи створити набір у Python:

  1. За допомогою фігурних дужок ({}), також відомих як фігурні дужки.

  2. Використовуючи вбудовану функцію set(), яка приймає один аргумент, ітерований елемент, що містить елементи, які ви хочете включити в набір.

Загальний синтаксис для створення набору Python за допомогою фігурних дужок і вбудованої функції set наведено нижче:

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

Що таке списки Python

Список Python — це вбудована структура даних, подібна до динамічних масивів в інших мовах програмування.

Вони використовуються для зберігання кількох елементів в одній змінній, що робить їх універсальним варіантом для обробки різних типів даних, таких як рядки, числа та логічні значення.

Списки Python мають такі властивості:

  1. Вони впорядковані, що означає, що певний елемент має унікальну позицію в списку та доступ до нього можна отримати через його індекс. Ця впорядкована колекція підтримує довільний доступ, дозволяючи вам виконувати такі операції, як нарізка, конкатенація та розуміння списку.

  2. Вони змінні, а їхні елементи можна змінювати після створення списку, що забезпечує гнучкість роботи зі структурами даних.

  3. Списки Python допускають повторювані значення та можуть зберігати комбінацію типів даних, включаючи рядки, числа та логічні значення.

Є два

  1. За допомогою квадратних дужок, які позначають межі списку.

  2. Використовуючи вбудовану функцію list(), яка може приймати один аргумент або ітерацію, що містить елементи, які ви хочете включити до списку.

Наступний код Python демонструє створення списку Python за допомогою квадратних дужок і вбудованої функції list():

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

3 ключові відмінності між наборами та списками

Це численні відмінності між набором Python і списком. Нижче наведено деякі з важливих.

1. Порядок та індексація

Порядок та індексування в списку: список 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 Set Vs List – справжня різниця

Набори 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 Set Vs List – справжня різниця

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 Set Vs List – справжня різниця

Набір 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 Set Vs List – справжня різниця

Унікальність елементів

Набори 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 Set Vs List – справжня різниця

    Списки 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 Set Vs List – справжня різниця

3. Підтримувані операції

Існують різні операції, які можна виконувати над наборами та списками, кожна з яких оптимізована для конкретних завдань:

Списки Python: через свою впорядковану та індексну природу списки підтримують такі операції, як нарізка, конкатенація, повторення та розуміння списку. Вони також надають вбудовані методи, такі як append(), pop() і sort(), які дозволяють вам маніпулювати елементами списку.

# 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 Set Vs List – справжня різниця

наприклад об’єднання, перетин, різниця та перевірка належності за допомогою хеш-функцій для швидкого пошуку елементів. Оскільки вони невпорядковані та не мають індексації, операції з наборами відрізняються від операцій зі списком.

# 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 Set Vs List – справжня різниця

Як вибрати правильну структуру даних?

Працюючи з Python, важливо вибрати структуру даних, яка найбільше підходить для конкретного завдання. У цьому розділі ми обговоримо найкращі сценарії використання наборів і списків, а також їхні унікальні переваги.

Давайте вникнемо в це.

Випадки використання наборів

Набори мають ряд переваг, які роблять їх ідеальним вибором для певних завдань:

Унікальність: якщо вам потрібно зберігати колекцію унікальних елементів, набори — це ваш шлях. Набори автоматично усувають дублікати, гарантуючи, що кожен елемент у наборі є відмінним.

Тести на членство: набори забезпечують швидші тести на членство порівняно зі списками. Завдяки реалізації базової хеш-таблиці та використанню хеш-функцій, набори дозволяють виконувати високоефективні пошуки на основі хеш-значень.

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. Iteration: Lists are slightly faster than sets when it comes to iterating over the items. This is because sets require additional operations to ensure uniqueness, while lists maintain a simple ordered collection with direct indexing.

Memory Usage

Sets typically consume more memory than lists because they need to maintain a hash table to ensure the uniqueness of items, which comes at the cost of increased memory consumption.

Lists only store the elements sequentially, leading to lower memory consumption, making them a more memory-efficient choice when handling large collections of data.

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")

The provided code showcases the performance comparison between Python sets and lists in terms of time complexity for searching and iteration.

It generates a large list and set of random integers, enclosed by curly brackets (also called curly braces).

It then measures the time taken to search for a specific item, using a single argument in both the list and set, and measures the time taken to iterate through all elements in the list and set.

Python Set Vs List – справжня різниця

The output illustrates the performance differences between Python lists and sets for search and iteration, which stem from their underlying implementation.

The search operation is faster in sets (0.000000 seconds) than in lists (0.002999 seconds) due to the use of hash functions to compute hash values for efficient lookups. However, iterating over a list (0.007995 seconds) is slightly faster than iterating over a set (0.017989 seconds) since sets require additional operations to ensure uniqueness.

Common Operations and Methods

Both sets and lists in Python have various operations and methods, each optimized for specific tasks and data manipulation. Some of these methods are listed below:

Set Method

Set methods perform operations that are similar to mathematical operations and are powerful tools for handling unique values in a collection.

  • add(element): Adds an element to the set if it is not already present.

  • remove(element): Removes the specified element from the set; raises an error if the element is not found.

  • discard(element): Removes the specified element from the set if it is present. No error is raised if the element is not found.

  • union(set2): Returns a new set containing all elements from the original set and set2, effectively performing a set operation.

  • intersection(set2): Returns a new set containing elements common to both the original set and set2.

  • difference(set2): Returns a new set containing elements in the original set but not in set2.

  • symmetric_difference(set2): Returns a new set containing elements in either the original set or set2, but not in both.

List Method

List methods provide various ways to manipulate data.

  • append(element): Adds an element to the end of the list.

  • extend(iterable): Appends all elements from the iterable (e.g., another list) to the end of the list.

  • insert(index, element): Inserts an element at the specified index.

  • remove(element): Removes the first occurrence of the specified element in the list; raises an error if the element is not present.

  • pop(index): Removes and returns the element at the specified index. If no index is given, it removes the last element.

  • index(element): Returns the index of the first occurrence of the specified element in the list.

  • count(element): Returns the number of occurrences of the specified element in the list.

  • sort(): Sorts the list in ascending order by default; for descending order, use the reverse=True parameter.

  • reverse(): Reverses the order of the elements in the list.

By using these Python set and list methods, you can effectively manipulate your data and solve various problems in Python programming, data science, and other applications.

Our Final Say

When choosing between Python lists and sets for your data structure, consider using lists when you need an ordered collection of items, want to preserve duplicate elements, and require the ability to access elements by index.

Opt for sets when the uniqueness of elements is essential, the order of elements is not important, and faster membership testing is preferred. While lists excel in iteration, sets provide more efficient containment checks.

Your choice ultimately depends on your project’s requirements, as each data structure offers its own set of benefits and limitations, making them powerful tools for tackling various tasks in Python programming. Enjoy!


Труба в R: підключення функцій за допомогою Dplyr

Труба в R: підключення функцій за допомогою Dplyr

У цьому підручнику ви дізнаєтесь, як об’єднати функції разом за допомогою оператора каналу dplyr мовою програмування R.

RANKX Deep Dive: функція LuckyTemplates DAX

RANKX Deep Dive: функція LuckyTemplates DAX

RANKX від LuckyTemplates дозволяє повернути рейтинг певного числа в кожному рядку таблиці, який є частиною списку чисел.

Вилучення тем і зображень LuckyTemplates із PBIX

Вилучення тем і зображень LuckyTemplates із PBIX

Дізнайтеся, як розібрати файл PBIX, щоб витягти теми та зображення LuckyTemplates із фону та використовувати їх для створення звіту!

Шпаргалка формул Excel: Посібник середнього рівня

Шпаргалка формул Excel: Посібник середнього рівня

Шпаргалка формул Excel: Посібник середнього рівня

Календарна таблиця LuckyTemplates: що це таке та як ним користуватися

Календарна таблиця LuckyTemplates: що це таке та як ним користуватися

Календарна таблиця LuckyTemplates: що це таке та як ним користуватися

Python у LuckyTemplates: як встановити та налаштувати

Python у LuckyTemplates: як встановити та налаштувати

Дізнайтеся, як інсталювати мову програмування Python у LuckyTemplates і як використовувати її інструменти для написання кодів і відображення візуальних елементів.

Розрахунок динамічної норми прибутку – легкий аналіз LuckyTemplates за допомогою DAX

Розрахунок динамічної норми прибутку – легкий аналіз LuckyTemplates за допомогою DAX

Дізнайтеся, як обчислювати динамічну маржу прибутку за допомогою LuckyTemplates і як ви можете отримати більше інформації, глибше досліджуючи результати.

Сортування стовпців таблиці дат у LuckyTemplates

Сортування стовпців таблиці дат у LuckyTemplates

Дізнайтеся, як правильно сортувати поля зі стовпців розширеної таблиці дат. Це хороша стратегія для складних полів.

Знайдіть свої найкращі продукти для кожного регіону в LuckyTemplates за допомогою DAX

Знайдіть свої найкращі продукти для кожного регіону в LuckyTemplates за допомогою DAX

У цій статті я поясню, як знайти найпопулярніші продукти для регіону за допомогою обчислень DAX у LuckyTemplates, включаючи функції TOPN і CALCULATE.

Вимір сміття: що це таке і чому це щось інше, але не сміття

Вимір сміття: що це таке і чому це щось інше, але не сміття

Дізнайтеся, як використовувати вимірювання сміття для позначок низької потужності, які ви хочете ефективно включити у свою модель даних.