elem is the abbreviation of the word “element”, representing an indeterminate type in programming definitions, i.e., an abstract data type.
List
Definition
A container formed by a sequence of elements arranged in order.
- Elements can be of any type.
- Elements are arranged in a determined order, exhibiting sequentiality.
Creating a List
Method 1: Create an empty list instance and then add elements
list().append()method
>>> wife = list() # Instantiation
>>> wife.append("Nishimiya Shoko")
>>> wife.append("Sakurajima Mai")
>>> wife.append("Elysia")
>>> wife
['Nishimiya Shoko', 'Sakurajima Mai', 'Elysia']
Method 2: Directly define and populate the list
>>> phones = ["Apple", "Huawei", "Xiaomi"]
>>> phones
['Apple', 'Huawei', 'Xiaomi']
Accessing Elements
Using Indexing
Access the (i+1)th element with[i].index()Methodname.index(x)
Searches for the first element with valuexin listnameand returns its index.count()Methodname.count(x)
Counts how many elements in listnamehave the valuexand returns the count.len()Methodlen(name)
Returns the total number of elements in listname.
Adding Elements
append()Methodname.append(x)
Adds elementxto the end ofname.insert()Methodname.insert(i, x)
Inserts objectxat indexiinname, shifting subsequent elements backward.extend()Methodname.extend(name2)
Appends listname2to the end of listname.
Modifying Elements
- Direct Assignment via Index
Assign a new value to an element using its index.
Deleting Elements
pop()Methodname.pop()
Removes the last element by default.name.pop(i)
Removes the element at indexi, shifting subsequent elements forward.remove()Methodname.remove(x)
Removes the first element with valuex, shifting subsequent elements forward.clear()Methodname.clear()
Deletes all elements (empties the list).delStatementdel name[a:b]
Deletes elements with indices in[a, b)(includesa, excludesb).del name[:]clears the list.del name[i]deletes the element at indexi.
Reversing a List
reverse()Methodname.reverse()
Reverses the list in place (last element becomes first, etc.).Slicing Method
>>> nums = [1, 2, 3, 4, 5] >>> new_nums = nums[::-1] >>> new_nums [5, 4, 3, 2, 1]The original list
numsremains unchanged; a new reversed listnew_numsis created.
Sorting a List
sort()Methodname.sort()name.sort(cmp=None, key=None, reverse=False)- Modifies the original list in place (no return value).
cmpis an optional parameter (deprecated in Python 3).keyspecifies a function to extract a comparison key from each element.- Omitted if elements are single-parameter (e.g., numbers or single characters).
def takeSecond(elem): return elem[1] random = [(2, 2), (3, 4), (4, 1), (1, 3)] random.sort(key=takeSecond) # Sorts by the second element of each tuple. print(random) # Output: [(4, 1), (2, 2), (1, 3), (3, 4)]reverse:Falsefor ascending (default),Truefor descending.
Tuple
Definition
A tuple is an immutable sequence of elements, similar to a list but unchangeable.
Creating a Tuple
- Use parentheses
()to enclose elements (lists use[]). - Sometimes tuples can be created without
()(not recommended). - Tuple Comprehension:
atuple = (i+1 for i in range(31, 42)) - For single-element tuples, add a trailing comma
,to avoid confusion with non-tuple objects. - Empty Tuple:
a = tuple() b = ()
Tuples Are Immutable
Tuples do not support addition, deletion, or modification of elements.
Converting Between Tuples and Lists
- Tuple → List:
atuple = (1, 'love', 3.334, 'Y') alist = list(atuple) # Converts to list - List → Tuple:
alist = ['I', 2, 3.1415, 'polaris'] atuple = tuple(alist) # Converts to tuple
Dictionary (dict)
Definition
- A collection of key-value pairs.
- Keys must be hashable (e.g., strings, numbers).
- Hash: A process that maps data of arbitrary size to fixed-size values.
- Values can be any object.
Creating a Dictionary
Empty Dictionary + Assignment:
profile = dict(name='孤筝', age=19, hobby='明月栞那')(Note: Keys as identifiers do not need quotes.)
Direct
{}Syntax:profile = {'name': '孤筝', 'age': 19, 'hobby': '明月栞那'}(Keys as strings require quotes.)
From Sequence of Pairs:
alist = [('name', '孤筝'), ('age', 19), ('hobby', '明月栞那')] profile = dict(alist)Dictionary Comprehension:
adict = {i: i**2 for i in range(2, 6)} # Output: {2: 4, 3: 9, 4: 16, 5: 25}
Accessing Elements
dict[key]:
RaisesKeyErrorif the key is missing.dict.get(key[, default]):
Returnsdefault(orNone) if the key is missing.
If the key is absent, it can optionally add the key with the default value.
Adding/Modifying Elements
- Add/Modify:
dict[key] = value
Deleting Elements
dict.pop(key): Removes the key-value pair.del dict[key]: Deletes the pair.
Other Key Methods
Checking Key Existence
in/not indict.has_key()(Python 2 only; removed in Python 3).
Setting Default Values
- Conditional Check:
if "gender" not in profile: profile["gender"] = "male" setdefault():dict.setdefault(key, default=None)
Setsdefaultif the key is missing.
Set
Definition
An unordered collection of unique elements (like a mathematical set).
Question: If sets are unordered, how are elements ordered when printed/stored?
Creating a Set
- Curly Braces
{}: Duplicates are automatically removed. set()Constructor:aset = {1314, '520'} bset = set() # Empty set cset = set(['I', 'love', 'ishimiya'])
Adding Elements
add():aset.add(elem)- No effect if
elemalready exists (no error). elemmust be immutable (e.g., numbers, strings).
- No effect if
update():aset.update(iterable)
Adds elements from any iterable (e.g., list, tuple, dict keys).
Deleting Elements
remove(): RaisesKeyErrorif the element is missing.discard(): No error if the element is missing.pop(): Randomly removes and returns an element.clear(): Empties the set.
Set Operations
Union
aset.union(bset) or aset | bset
Difference
aset.difference(bset) or aset - bset
Intersection
intersection():aset.intersection(bset)oraset & bsetintersection_update(): Updatesasetin place.
Symmetric Difference (Non-Overlapping Elements)
symmetric_difference(): Returns new set.symmetric_difference_update(): Updatesasetin place.
Other Operations
- Membership Check:
elem in aset - Disjoint Check:
aset.isdisjoint(bset)(True if no common elements). - Subset Check:
bset.issubset(aset)(True ifbsetis a subset).
Iterator
Iterable Objects
Objects usable in for loops (e.g., lists, tuples).
Iterable Protocol
- Implements
__iter__(): Returns an iterator instance.isinstance(obj, Iterable)returnsTrue.
- Fallback to
__getitem__(): If__iter__()is missing, Python checks for__getitem__()to simulate iteration.isinstance(obj, Iterable)returnsFalsefor this case.
Iterator Objects
- Created via
iter(iterable). - Elements are accessed using
next(), raisingStopIterationwhen exhausted.
alist = ['人', '生', '若', '只', '如', '初', '见']
gen = iter(alist)
for _ in alist:
print(next(gen)) # Outputs elements sequentially
Iterable vs. Iterator
- Iterable: The container (e.g., list).
- Iterator: The object returned by
iter(), enabling element-by-element traversal.
Generator
A function that produces values lazily (like an iterator), usable in for loops.
Creating Generators
List Comprehension → Generator
alist = [i for i in range(5)] # List
gen = (i for i in range(5)) # Generator
print(next(gen)) # Output: 0
yield Keyword
- Pauses function execution and returns a value.
- Resumes from the paused state on subsequent calls.
def generator():
top = 5
i = 0
while i < top:
print(f'Current value: {i}')
i += 1
yield i
raise StopIteration
gen = generator()
for _ in range(5):
print(next(gen))
Key Difference: yield vs. return
yieldpauses execution;returnterminates it.yieldcan resume;returncannot.

When will I have a drink and discuss the details again?