Python list() Function (original) (raw)
Last Updated : 04 Mar, 2025
list() function in Python is used to create lists from iterable objects. An iterable is an object that can be looped over, such as strings, tuples, sets, dictionaries and other collections. The function provides a convenient way to convert these objects into lists, making it easier to manipulate and process their elements. Example:
Python `
s = "Python"
Using list()
res = list(s) print(res)
`
Output
['P', 'y', 't', 'h', 'o', 'n']
**Explanation: String “Python” has six characters. list(s) converts it into [‘P’, ‘y’, ‘t’, ‘h’, ‘o’, ‘n’] by iterating through each character.
list() syntax
list(iterable)
**Parameters:
- **iterable (optional): An iterable object (such as a string, tuple, set, dictionary, or another iterator) that is converted into a list.
- If no argument is passed, it returns an empty list: [].
**Returns: Returns a new list containing elements from the given iterable.
Examples of list()
**Examples 1: Creating a list from a tuple
Python `
tup = (10, 20, 30, 40)
converting tuple to list
res = list(tup) print(res)
`
**Explanation: Tuple tup has four elements. **list(tup) converts it into [10, 20, 30, 40] by iterating through each element.
**Example 2: Creating a List from a Set
Python `
a = {1, 2, 3, 4, 5}
converting set to list
res = list(a) print(res)
`
**Explanation: Set **a has five elements. **list(a) converts it into a list, but the order may vary since sets are unordered.
**Example 3: Creating a list from a dictionary
Python `
d = {'A': 10, 'B': 20, 'C': 30}
Converting dictionary to list
res = list(d) print(res)
`
**Explanation: dictionary **d has three key-value pairs. **list(d) converts it into [‘A’, ‘B’, ‘C’], as **list() extracts only the dictionary keys.
**Example 4: Taking user inputs as a list
Python `
taking user input
a = list(input("Enter list elements: "))
print(a)
`
**Output
Enter list elements: Hello
['H', 'e', 'l', 'l', 'o']
**Explanation: This code takes user input as a string and converts it into a list of individual characters using list().