Python Set versus List – skutečný rozdíl

Ve světě programování v Pythonu se často setkáte s různými datovými strukturami, které slouží různým účelům. Mezi těmito strukturami, množinami a seznamy se běžně používají k ukládání a manipulaci s kolekcemi dat.

I když se mohou zdát podobné, existují výrazné rozdíly v jejich vlastnostech a případech použití.

Python Set versus List – skutečný rozdíl

Obsah

Pochopení sad a seznamů Pythonu

Dobře, tak si nejprve věci vysvětlíme.

Co jsou sady Python?

Sada je vestavěná datová struktura, která představuje neuspořádanou kolekci odlišných prvků, nazývaných členy.

Tento mocný nástroj je zvláště užitečný v aplikacích datové vědy a matematických operacích.

Sady Pythonu mají následující vlastnosti:

  1. Jsou neuspořádané, což znamená, že prvky v sadě jsou uloženy nezávisle na jejich indexu. Tato neuspořádaná sbírka jedinečných hodnot podporuje účinné testy členství a porozumění sadám.

  2. Neumožňují duplicitní hodnoty. Díky tomu jsou užitečné, když potřebujete pracovat s jedinečnými hodnotami, odstraňovat duplikáty ze seznamu nebo provádět operace sady, jako jsou sjednocení, průniky a symetrické rozdíly.

Existují dva způsoby, jak vytvořit sadu v Pythonu:

  1. Pomocí složených závorek ({}), známých také jako složené závorky.

  2. Pomocí vestavěné funkce set() , která přebírá jeden argument, iterovatelný prvek obsahující prvky, které chcete zahrnout do sady.

Obecná syntaxe pro vytvoření sady Python pomocí složených závorek a vestavěné funkce sady je uvedena níže:

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

Co jsou seznamy Pythonu

Seznam Pythonu je vestavěná datová struktura podobná dynamickým polím v jiných programovacích jazycích.

Používají se k ukládání více položek do jedné proměnné, což z nich činí všestrannou možnost pro práci s různými datovými typy, jako jsou řetězce, čísla a booleany.

Python Listy mají následující vlastnosti:

  1. Jsou seřazeny, což znamená, že určitý prvek má v seznamu jedinečnou pozici a lze k němu přistupovat prostřednictvím jeho indexu. Tato uspořádaná kolekce podporuje náhodný přístup, což vám umožňuje provádět operace, jako je dělení, zřetězení a porozumění seznamu.

  2. Jsou proměnlivé a jejich prvky lze po vytvoření seznamu změnit, což nabízí flexibilitu při práci s datovými strukturami.

  3. Seznamy Pythonu umožňují duplicitní hodnoty a mohou ukládat různé typy dat, včetně řetězců, čísel a booleanů.

Existují dva

  1. Pomocí hranatých závorek, které označují hranice seznamu.

  2. Pomocí vestavěné funkce list() , která může převzít jeden argument nebo iteraci obsahující prvky, které chcete zahrnout do seznamu.

Následující kód Pythonu ukazuje vytvoření seznamu Python pomocí hranatých závorek a vestavěné funkce list():

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

3 Klíčové rozdíly mezi sadami a seznamy

Jedná se o několik rozdílů mezi sadou Pythonu a seznamem. Některé z důležitých jsou uvedeny níže:

1. Objednávka a indexování

Pořadí a indexování v seznamu: Seznam Python může podporovat indexování, což znamená, že k prvkům v seznamu můžete přistupovat pomocí jejich pozice v seznamu. To poskytuje flexibilitu při manipulaci s daty se známou objednávkou.

Následující kód ukazuje pořadí a indexování seznamů:

# 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 versus List – skutečný rozdíl

Sady Pythonu: Sada Pythonu je neuspořádaná kolekce bez indexování, což znamená, že nemůžete přistupovat k prvkům pomocí jejich pozice. To je užitečné, když na pořadí prvků nezáleží.

Následující kód Pythonu demonstruje sady pořadí a indexování:

# 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 versus List – skutečný rozdíl

2. Proměnlivost

Seznam Pythonu: Seznam Pythonu je proměnlivý, což vám umožňuje upravovat jeho prvky. Mohou obsahovat jakýkoli typ objektu, včetně vnořených seznamů, čímž nabízejí větší flexibilitu, pokud jde o obsah, který mohou ukládat.

Následující kód demonstruje proměnlivost v seznamech Pythonu:

# 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 versus List – skutečný rozdíl

Sada Pythonu: Stejně jako v Pythonu je i sada Python proměnlivá a lze ji upravit. Sady v Pythonu však mohou obsahovat pouze hašovatelné (neměnné) objekty, což znamená, že nemůžete mít sadu sad nebo sadu obsahující měnitelné objekty, jako jsou seznamy.

Následující kód demonstruje proměnlivost sad Pythonu:

# 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 versus List – skutečný rozdíl

Jedinečnost prvků

Sady Pythonu: Klíčovou vlastností sad je, že ukládají pouze jedinečné prvky. Přidání duplicitních hodnot do seznamu je ignorováno. Díky tomu je objekt sady ideální pro různé operace sady, jako je odstraňování duplikátů nebo kontrola přítomnosti jedinečných prvků.

# 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 versus List – skutečný rozdíl

    Seznamy Pythonu: Seznamy umožňují duplicitní hodnoty a udržují jejich pořadí, což může být zásadní v případech použití, kdy duplikáty a pořadí prvků hrají významnou roli.

    # 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 versus List – skutečný rozdíl

3. Podporované operace

Na sadách a seznamech lze provádět různé operace, z nichž každá je optimalizována pro konkrétní úkoly:

Seznamy Python: Vzhledem ke své uspořádané a indexované povaze seznamy podporují operace, jako je dělení, zřetězení, opakování a porozumění seznamu. Poskytují také vestavěné metody, jako je append(), pop() a sort(), které umožňují manipulovat s prvky seznamu.

# 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 versus List – skutečný rozdíl

jako sjednocení, průnik, rozdíl a kontrola členství pomocí hashovacích funkcí k rychlému nalezení prvků. Protože jsou neuspořádané a postrádají indexování, operace množin se liší od operací založených na seznamu.

# 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 versus List – skutečný rozdíl

Jak zvolíte správnou datovou strukturu?

Při práci s Pythonem je nezbytné vybrat nejvhodnější datovou strukturu pro váš konkrétní úkol. V této části probereme nejlepší scénáře použití sad a seznamů spolu s jejich jedinečnými výhodami.

Pojďme do toho.

Případy použití pro sady

Sady nabízejí několik výhod, díky kterým jsou ideální volbou pro určité úkoly:

Jedinečnost: Pokud potřebujete uložit sbírku jedinečných prvků, sady jsou správnou volbou. Sady automaticky odstraňují duplikáty a zajišťují, že každý prvek v sadě je odlišný.

Testy členství: Sady poskytují rychlejší testy členství ve srovnání se seznamy. Díky jejich základní implementaci hashovací tabulky a použití hashovacích funkcí umožňují sady vysoce efektivní vyhledávání založené na hodnotách hash.

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 versus List – skutečný rozdíl

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!


Alokace rozpočtu: Měsíční předpovědi napříč denními výsledky v LuckyTemplates

Alokace rozpočtu: Měsíční předpovědi napříč denními výsledky v LuckyTemplates

V tomto tutoriálu projdu algoritmem alokace rozpočtu v LuckyTemplates, kde porovnáte měsíční prognózy a denní prodeje.

Použití pokročilé logiky v LuckyTemplates k opravě vašich součtů

Použití pokročilé logiky v LuckyTemplates k opravě vašich součtů

Zjistěte, jak můžete získat správné součty ve výpočtech pomocí pokročilých vzorců DAX a pokročilé logiky v LuckyTemplates.

Zobrazení a formuláře PowerApps: Jak vytvářet a přizpůsobovat

Zobrazení a formuláře PowerApps: Jak vytvářet a přizpůsobovat

Přečtěte si další informace o zobrazeních a formulářích PowerApps a o tom, jak je vytvářet a přizpůsobovat speciálně pro aplikaci, kterou vytváříte.

Rozšířené šablony výkazů LuckyTemplates – koncepty vizualizace LuckyTemplates

Rozšířené šablony výkazů LuckyTemplates – koncepty vizualizace LuckyTemplates

V tomto blogovém tutoriálu se ponořím do toho, jak přizpůsobit šablony výkazů LuckyTemplates a jak efektivně vizualizovat finanční informace a data.

Návrh sestav LuckyTemplates – neomezené možnosti

Návrh sestav LuckyTemplates – neomezené možnosti

Takto vypadá skvělý design sestav LuckyTemplates. Jedná se o předpřipravený design, který využívá nápovědu a záložky s impozantní navigací.

LuckyTemplates UŽIVATELSKÝ VZTAH Vs. TREATAS

LuckyTemplates UŽIVATELSKÝ VZTAH Vs. TREATAS

Naučte se rozdíl mezi funkcí LuckyTemplates USERELATIONSHIP a funkcí TREATAS, které se obě používají při vytváření mír DAX.

Zcela nový kurz: Microsoft Excel pro začátečníky

Zcela nový kurz: Microsoft Excel pro začátečníky

Zcela nový kurz: Microsoft Excel pro začátečníky

Funkce ISNULL SQL v příkazech případu

Funkce ISNULL SQL v příkazech případu

Naučte se a pochopte, jak můžete použít příkaz CASE spolu s funkcí ISNULL SQL k vrácení hodnoty, když je hodnota NULL.

Design řídicího panelu LuckyTemplates – působivý nápad na vizualizaci otáčení stránek

Design řídicího panelu LuckyTemplates – působivý nápad na vizualizaci otáčení stránek

Příklady řídicího panelu LuckyTemplates, naučte se a pochopte, jak vytvořit nejinovativnější vzhled vizualizace pro otáčení stránek pro návrh řídicího panelu LuckyTemplates v těchto jednoduchých krocích!

Scatter Plot In R Script: Jak vytvořit a importovat

Scatter Plot In R Script: Jak vytvořit a importovat

V tomto tutoriálu se naučíte, jak vytvořit vizualizaci R bodového grafu v LuckyTemplates pomocí vizuálu R Script.