Remember
list() builds a mutable list from an iterable. Constructing a list from text gives one element per character.
list() builds a mutable list from an iterable. Constructing a list from text gives one element per character.
Follow the example, change its sample, and compare what happens.
Explain the result and test your understanding.
Focus on how the names, objects, and calculations change. We’ll inspect the printed output in the next section.
Follow the code and watch its state change. Guided simulation.
text = 'tea'
items = list(text)
print(items)Top-level scope
'tea'Object 2 · list['t', 'e', 'a']list() builds a mutable list from an iterable. Constructing a list from text gives one element per character.
(no output)
What do you expect this program to print?
EXAMPLE INSTRUCTIONS
text = 'tea'
items = list(text)
print(items)
|
v
DISPLAYED RESULT
['t', 'e', 'a']
FINAL BINDINGS
text --> object 1 (str)
items --> object 2 (list)
object 1: 'tea'
object 2: ['t', 'e', 'a']Choose a different sample input, then follow every step through to the output. Before revealing it, predict what the program will display.
Choose a sample and follow its execution. Guided simulation.
text = 'tea'
items = list(text)
print(items)Top-level scope
'tea'Object 2 · list['t', 'e', 'a']The example has finished. Compare the final output with the values and references above.
['t', 'e', 'a']
What do you expect this program to print?
text = 'tea'
items = list(text)
print(items)list() FunctionThe list() function in Python is used to create a new list. It can also be used to convert other iterable data types like strings, tuples, or sets into a list.
list([iterable])
iterable (optional) – An iterable object like string, tuple, set, or dictionary.my_list = list()
print(my_list)
[]
my_list = list("hello")
print(my_list)
['h', 'e', 'l', 'l', 'o']
my_list = list((1, 2, 3))
print(my_list)
[1, 2, 3]
my_list = list({10, 20, 30})
print(my_list)
[10, 20, 30]
my_dict = {'a': 1, 'b': 2}
my_list = list(my_dict)
print(my_list)
['a', 'b']
Note: Only the keys of the dictionary are added to the list.
my_list = list assigns the function, not a list.list(5) will throw TypeError because int is not iterable.In interviews, the list() function is often used to convert generators or iterators to lists for easier access and manipulation.
list() creates a list from an iterable or creates an empty list.Convert the string "Tutorial" into a list of characters, and print it.
word = "Tutorial"
letters = list(word)
print(letters)
Connect what you noticed in the example with the idea below.
list() builds a mutable list from an iterable. Constructing a list from text gives one element per character.
list(text) always makes a single-element list containing the full text.
This is the misconception to avoid.Reference checks are optional and do not count toward course progress.