Post

Difference Between [result] and list(result)

Let's Understand `[result]` and `list(result)` in Python

Difference Between [result] and list(result)

I used to treat [result] and list(result) as interchangeable ways to convert a variable into a list. However, while working with the return values from PyMilvus recently, I came to realize there’s a significant difference between the two. I decided to document this insight in a blog post.

[result]

Using [result] means you are manually creating a list with one item — the variable result itself. I think that “Make a list containing this one thing.”

1
2
3
4
5
6
7
8
9
10
11
12
result = 123
print([result])  # [123]

result = 'abc'
print([result])  # ['abc']

result = (x for x in range(3)) # A generator
converted = [result]
print(converted) # [<generator object <genexpr> at 0x0000016291977780>]

for item in converted[0]:
    print(item) # Output: [0, 1, 2]

list(result)

Using list(result) converts an iterable (like a string, tuple, set, generator, or custom class with __iter__) into a list by iterating over its items. I think that “Iterate over this and collect all elements in a list.”

1
2
3
4
5
6
7
8
9
10
result = 123
print(list(result))  # TypeError: 'int' object is not iterable

result = 'abc'
print(list(result))  # ['a', 'b', 'c']

result = (x for x in range(3))  # A generator
converted = list(result)
print(converted)  # Output: [0, 1, 2]

Key Difference

Feature[result]list(result)
PurposeWrap a single objectConvert an iterable to a list
Input typeAny objectMust be iterable
Output sizeAlways length = 1Varies based on number of elements in input
Use caseNormalize single item as listFlatten iterable into list

Real-World Use Case: PyMilvus Hit vs. Hits

Let’s say I’m working with PyMilvus, and I get search results as either:

  • Hit: a single result
  • Hits: a list-like object of multiple results

I will use:

1
2
3
4
5
6
7
8
9
from pymilvus.client.search_result import Hit, Hits

if isinstance(result, Hit):
    result = [result]  # wrap it as a one-element list
elif isinstance(result, Hits):
    result = list(result)  # convert Hits to a plain list

for idx, item in enumerate(result):
	print(item['distance'])
This post is licensed under CC BY 4.0 by the author.