Python 3 – List list() Method
The list() method in Python 3 is used to create a new list object. This method is useful when you need to create a new list object that contains the same elements as another list object. The list() method can take any iterable object as its argument, such as a string, tuple or dictionary. In this article, we will explore the list() method in detail.
Syntax
The syntax for the list() method is as follows:
list(iterable)
Here, iterable is an object that can be iterated over such as a string, tuple, dictionary, etc.
Parameters
The list() method takes only one parameter:
- iterable – the iterable object that we want to convert into a list.
Example 1: Creating a List from a String
Let’s start by creating a new list object from a string.
>>> my_string = "Hello World"
>>> my_list = list(my_string)
>>> print(my_list)
['H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd']
In this example, we have created a string object called my_string
. We then use the list()
function to create a new list object called my_list
that contains the same elements as the string object.
Example 2: Creating a List from a Tuple
We can also create a new list object from a tuple object.
>>> my_tuple = (1, 2, 3, 4, 5)
>>> my_list = list(my_tuple)
>>> print(my_list)
[1, 2, 3, 4, 5]
In this example, we have created a tuple object called my_tuple
. We then use the list()
function to create a new list object called my_list
that contains the same elements as the tuple object.
Example 3: Creating a List from a Dictionary
We can also create a new list object from a dictionary object.
>>> my_dict = {"name": "John", "age": 30}
>>> my_list = list(my_dict)
>>> print(my_list)
['name', 'age']
In this example, we have created a dictionary object called my_dict
. We then use the list()
function to create a new list object called my_list
that contains the keys of the dictionary object.
Conclusion
In this article, we have explored the list() method in detail. We have seen how we can use this method to create a new list object from an iterable object such as a string, tuple or dictionary. The list() method is a powerful tool that can make it easier to work with lists in Python 3.