List Casting
Part of the Logic & Flow section of Coddy's Python journey — lesson 6 of 78.
You can use the list() function to cast iterables like tuples, strings, or ranges into lists. This is useful for working with elements in a modifiable format.
Casting a tuple to a list:
my_tuple = (1, 2, 3)
my_list = list(my_tuple)
print(my_list) # [1, 2, 3]Casting a string splits it into individual characters:
my_string = "hello"
my_list = list(my_string)
print(my_list) # ['h', 'e', 'l', 'l', 'o']Casting a range to a list gives all the numbers at once:
my_range = range(5)
my_list = list(my_range)
print(my_list) # [0, 1, 2, 3, 4]You can also cast to other types like set or dict, but you’ll explore those later. For now, focus on list() to handle and transform data flexibly!
Challenge
EasyConvert the following data into lists using the list() function:
- A tuple:
(10, 20, 30) - A string:
"python" - A range:
range(1, 6)
Print the resulting lists.
Example Output:
[10, 20, 30]
['p', 'y', 't', 'h', 'o', 'n']
[1, 2, 3, 4, 5]This challenge reinforces using list() to cast different iterables into lists.
Cheat sheet
Use the list() function to cast iterables like tuples, strings, or ranges into lists:
Casting a tuple to a list:
my_tuple = (1, 2, 3)
my_list = list(my_tuple)
print(my_list) # [1, 2, 3]Casting a string splits it into individual characters:
my_string = "hello"
my_list = list(my_string)
print(my_list) # ['h', 'e', 'l', 'l', 'o']Casting a range to a list gives all the numbers at once:
my_range = range(5)
my_list = list(my_range)
print(my_list) # [0, 1, 2, 3, 4]Try it yourself
# Write code hereThis lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Logic & Flow
1Variables Exploration
ConstantsMultiple Variable AssignmentsSwapping VariablesPlaceholder VariablesRound NumbersList Casting4Contact Book Application
Display MenuAdd Contact7Sets Part 2
Mathematical Operations Part 1Mathematical Operations Part 2Recap - Treasure HuntSubsets and SupersetsIterating Over SetsRecap - Tournament Tracker2Dictionaries Part 1
What is a Dictionary?Creating a DictionaryAccessing ValuesModifying DictionariesRecap - Recipe Manager5Advanced Decision Making
Ternary OperatorMembership ChecksIdentity ChecksIndentation ErrorsRecap - Vacation Filter8Student Records Manager
Project OverviewAdd Student11Advanced Functions
Returning Multiple ValuesLambda Functions Part 1Lambda Functions Part 2Recap Challenge - Lambda SortRecursive Functions Part 1Recursive Functions Part 2Recap - Sum Nested List14Higher-Order Functions
The Map FunctionThe Filter FunctionRecap - Email ValidatorRecap - Number Processor3Dictionaries Part 2
Dictionary MethodsNested DictionariesChecking for KeysLooping Through DictionariesRecap - Frequency Counter9Advanced Data Aggregation
Using SumFinding Minimum and MaximumSorting Data EfficientlyRecap - Dictionary Sorter