The list()
function creates a new list or converts an iterable (tuple, string, set, dictionary) into a list. It’s useful for managing collections, modifying sequences, and handling dynamic data.
Example
nums = list((1, 2, 3)) # Convert tuple to list
print(nums)
# Output: [1, 2, 3]
This converts a tuple into a list, allowing modifications.
Syntax
list(iterable)
- iterable (optional) → A sequence (
tuple
,string
,range
,set
,dictionary
). - Returns → A new list.
1. Creating an Empty List
empty_list = list()
print(empty_list)
# Output: []
Equivalent to []
.
2. Converting a String to a List
text = "hello"
letters = list(text)
print(letters)
# Output: ['h', 'e', 'l', 'l', 'o']
Breaks each character into a list element.
3. Converting a Range to a List
nums = list(range(5))
print(nums)
# Output: [0, 1, 2, 3, 4]
Useful for generating sequences dynamically.
4. Converting a Set to a List
unique_nums = list({3, 1, 2})
print(unique_nums)
# Output: [3, 1, 2] (Order may vary)
Useful when ordering unique elements.
5. Extracting Dictionary Keys and Values as Lists
data = {"name": "Alice", "age": 30}
keys = list(data.keys())
values = list(data.values())
print(keys) # Output: ['name', 'age']
print(values) # Output: ['Alice', 30]
Great for processing dictionary data.
Key Notes
- ✔ Creates an empty list if no argument is given.
- ✔ Converts tuples, strings, sets, and dictionaries into lists.
- ✔ Useful for dynamic collections and modifying sequences.
- ✔ Dictionary conversion returns only keys unless specified.
By using list()
, you can efficiently store, modify, and process collections of data. 🚀