0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

データ構造 - 入門

0
Posted at

Python Data Structures — Syntax Cheat Sheet for Beginners

1. Basic Syntax: [] vs {} vs ()

Symbol Name Usage
[] Square Brackets Create List / Access by Index or Key / Slicing
{} Curly Braces Create Set / Dictionary
() Parentheses Call Function or Method / Create Tuple / Group expressions
. Dot Operator Access Method or Attribute

Important: Creating a Data Structure and accessing its elements are different operations.

# Create a Dictionary: use {}
myDict = {"bob": 10}

# Access a Value by Key: use []
print(myDict["bob"])  # 10

# Call a Method: use ()
print(myDict.get("bob"))  # 10

2. Initialize Data Structures

2.1 Basic Initialization

# List (Array)
arr = [1, 2, 3]

# String
s = "hello"

# Tuple
t = (1, 2, 3)

# HashSet
mySet = {1, 2, 3}

# HashMap (Dictionary)
myDict = {"bob": 1, "alice": 2}

# Deque (Double-Ended Queue)
from collections import deque
q = deque([1, 2, 3])

2.2 Initialize Empty Data Structures

arr = []       # Empty List
s = ""         # Empty String
t = ()         # Empty Tuple
mySet = set()  # Empty Set
myDict = {}    # Empty Dictionary
q = deque()    # Empty Deque

Note:

  • {} creates an empty Dictionary, NOT a Set.
  • To create an empty Set, use set().
  • To create a Tuple containing one element, use (1,).

3. Access / Search Elements

3.1 Access by Index

# List
arr = [10, 20, 30]
print(arr[0])  # 10

# String
s = "hello"
print(s[0])  # h

# Tuple
t = (10, 20, 30)
print(t[0])  # 10

# Deque
q = deque([10, 20, 30])
print(q[0])  # 10

3.2 Access by Key (Dictionary)

myDict = {"bob": 10, "alice": 20}

print(myDict["bob"])       # 10
print(myDict.get("bob"))   # 10

Difference:

myDict["jack"]      # KeyError
myDict.get("jack")  # None

3.3 Check Value Existence (Membership)

# List
arr = [10, 20, 30]
print(20 in arr)  # True

# Set
mySet = {10, 20, 30}
print(20 in mySet)  # True

# Dictionary: checks Keys
myDict = {"bob": 10}
print("bob" in myDict)  # True
print(10 in myDict)     # False

# Dictionary: checks Values
print(10 in myDict.values())  # True

3.4 Unsupported Operations

mySet = {10, 20, 30}
# mySet[0]          # TypeError

myDict = {"bob": 10}
# myDict[0]         # KeyError, unless key 0 exists

s = "hello"
# s[0] = "H"        # TypeError (Immutable)

t = (1, 2, 3)
# t[0] = 10         # TypeError (Immutable)

Comparison

Data Structure Index Access Key Lookup Membership Check
List ✅ ❌ ✅
String ✅ ❌ ✅
Tuple ✅ ❌ ✅
Set ❌ ❌ ✅
Dictionary ❌ Positional Index ✅ ✅ Keys
Deque ✅ ❌ ✅

Note: A Dictionary uses Keys, not positional Indexes. An integer can be a Dictionary Key, but that does not make it a positional index.


4. Add / Update / Delete

4.1 List

arr = [1, 2, 3]

arr.append(4)     # Add to end
arr.insert(0, 0)  # Insert at index 0

arr[0] = 10       # Update by index

arr.pop()         # Remove last element
arr.pop(0)        # Remove first element

4.2 Set

mySet = {1, 2, 3}

mySet.add(4)       # Add Value
mySet.remove(2)    # Remove Value
mySet.discard(10)  # Remove if exists (no error)

Set does NOT support:

# mySet[0] = 10    # Invalid
# mySet.append(4)  # Invalid

4.3 Dictionary

myDict = {"bob": 10}

myDict["alice"] = 20  # Add new Key-Value Pair

myDict["bob"] = 100   # Update existing Value

myDict.pop("bob")     # Delete by Key

4.4 Deque

from collections import deque

q = deque([1, 2, 3])

q.append(4)       # Add right
q.appendleft(0)   # Add left

q.pop()           # Remove right
q.popleft()       # Remove left

4.5 String / Tuple

String and Tuple are Immutable.

s = "hello"

# s[0] = "H"      # Invalid

s = "H" + s[1:]   # Create a new String
print(s)          # Hello

5. Iterate Through Data Structures

5.1 List / String / Tuple / Set / Deque

arr = [1, 2, 3]

for x in arr:
    print(x)

For a Set:

mySet = {1, 2, 3}

for value in mySet:
    print(value)

Set does not guarantee iteration order.

5.2 Dictionary — Three Methods

hashMap = {
    "apple": 10,
    "orange": 20,
    "durian": 100
}

Method 1: Iterate through Keys

for key in hashMap:
    print(key, hashMap[key])

Method 2: Iterate through Values

for value in hashMap.values():
    print(value)

Method 3: Iterate through Key-Value Pairs

for key, value in hashMap.items():
    print(key, value)

.items() supports Tuple Unpacking:

key, value = ("apple", 10)

6. Comprehension Syntax

List Comprehension

arr = [i for i in range(5)]

# [0, 1, 2, 3, 4]

Set Comprehension

mySet = {i for i in range(5)}

# {0, 1, 2, 3, 4}

Dictionary Comprehension

myDict = {str(i): i**2 for i in range(5)}

# {'0': 0, '1': 1, '2': 4, '3': 9, '4': 16}

Remember:

  • [] → List Comprehension
  • {value for ...} → Set Comprehension
  • {key: value for ...} → Dictionary Comprehension

7. Function vs Method

Function

arr = [1, 2, 3]

print(len(arr))   # 3
print(max(arr))   # 3

Syntax:

function(arguments)

Method

arr.append(4)
arr.pop()

mySet.add(10)

myDict.get("bob")

Syntax:

object.method(arguments)

Important:

myDict["bob"]       # Access by Key
myDict.get("bob")   # Method Call

arr[0]              # Access by Index
arr.append(5)       # Method Call

8. Time Complexity Cheat Sheet

Data Structure Access Search Insert / Add
List O(1) by Index O(n) O(1) amortized at end
String O(1) by Index O(n) for character O(n) concatenation
Tuple O(1) by Index O(n) ❌ Immutable
Set ❌ No Index O(1) average O(1) average
Dictionary O(1) average by Key O(1) average by Key O(1) average
Deque O(1) at ends; O(n) middle O(n) O(1) at ends

Notes:

  • n = Number of Elements (or String Length).
  • HashSet / HashMap operations are O(1) on average, but can be O(n) in the worst case.
  • For String, the O(n) search above refers to looking for a single character.
  • List .pop(0) takes O(n), while Deque .popleft() takes O(1).

9. Common Mistakes

Incorrect Correct Reason
myDict("bob") myDict["bob"] Key Access uses []
myDict.add("a", 1) myDict["a"] = 1 Dictionary has no .add()
mySet.append(5) mySet.add(5) Set uses .add()
mySet[0] 0 in mySet Set has no Index
{} for Empty Set set() {} creates Dictionary
arr.add(5) arr.append(5) List uses .append()
s[0] = "H" s = "H" + s[1:] String is Immutable
myDict.values myDict.values() Calling the Method requires ()

10. Quick Rules for LeetCode

  • List: Use when you need ordered elements and Index Access.
  • String: Use for text; remember it is Immutable.
  • Tuple: Use for fixed, ordered collections.
  • Set: Use when you need to check whether a Value exists quickly.
  • Dictionary: Use when you need to map a Key to a Value.
  • Deque: Use for efficient insertion and removal from both ends.

Final Reminder

[] = Create List OR Access Element

{} = Create Set / Dictionary

() = Call Function / Method OR Create Tuple / Group Expressions

. = Access Method / Attribute

in = Membership Check OR Iterate in a for Loop

The most important distinction is:

Creating a Data Structure ≠ Accessing its Elements ≠ Calling its Methods.

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?