martes, 11 de junio de 2024

summary of the information about different data structures in

Here's an organized summary of the information about different data structures in Python, along with methods to iterate over them as key-value pairs when applicable:

Feature by Data Structure

FeatureDictionarySetListStringTuple
DefinitionStores key
pairs
An unordered collection of unique elementsA sequential, mutable collection of any data typeA sequential, immutable collection of textual dataA sequential, immutable collection of any data type
Representation{ 'a':[42], 'b':[23,6,1] }{'^2', 'mc', 'equal', 'E'}[ 'a','b', 3, 4 ]"call me ishmael"( 'commander','lambda')
How to create?x = {}, x = dict()x = set()x = [], x = list()x = "", x = str()x = ('a','b',), x = tuple()
Is structure mutable and allow duplicate elements?Immutable keys but mutable and duplicate valuesMutable but unique elements onlyMutable and allows duplicate elementsImmutable but allows duplicate elementsImmutable but allows duplicate elements
Is the structure iterable?Yes (iterable over keys)YesYesYesYes

Methods and Iteration

Dictionary

  • Methods: items(), keys(), values()
  • Iteration:
    python
    d = { 'a': [42], 'b': [23, 6, 1] } for key, value in d.items(): print(f"{key}: {value}")

Set

  • Methods: No key-value methods, primarily add(), remove(), union(), etc.
  • Iteration:
    python
    s = {'^2', 'mc', 'equal', 'E'} for element in s: print(element)

List

  • Methods: Index-based methods, append(), extend(), insert(), remove(), etc.
  • Iteration:
    python
    l = ['a', 'b', 3, 4] for index, value in enumerate(l): print(f"{index}: {value}")

String

  • Methods: String-specific methods, split(), join(), find(), replace(), etc.
  • Iteration:
    python
    s = "call me ishmael" for index, char in enumerate(s): print(f"{index}: {char}")

Tuple

  • Methods: Tuple-specific methods, mainly count() and index()
  • Iteration:
    python
    t = ('commander', 'lambda') for index, value in enumerate(t): print(f"{index}: {value}")

Summary

  • Dictionary: Best for key-value paired data, mutable values, and iterable over keys.
  • Set: Ideal for unique, unordered data, mutable, but no key-value pairs.
  • List: Great for ordered, mutable collections with duplicates allowed.
  • String: Immutable text data, iterated as characters.
  • Tuple: Immutable ordered collections, can contain duplicates.

No hay comentarios:

Publicar un comentario