Python List list() Method



The Python List list() method is used to convert an object into a list. This method accepts sequence type objects as arguments and converts them to lists. These sequence types can be anything: sets, tuples, strings, dictionaries etc.

As we might already know, objects in Python are divided into two categories: mutable and immutable. Lists, sets and dictionaries are mutable objects while tuples and strings are immutable. So when this method converts a tuple or a string into a list, the object becomes mutable.

Note: When a dictionary is converted into a list, only the keys of this dictionary become the elements of list whereas the values are neglected.

Syntax

Following is the syntax for list() method −

list(seq)

Parameters

  • seq − This is a tuple to be converted into list.

Return Value

This method returns the list after conversion.

Example

The following example shows the usage of the Python List list() method. Here, we are trying to convert a tuple into a list.

aTuple = (123, 'xyz', 'zara', 'abc')
aList = list(aTuple)
print("List elements : ", aList)

When we run above program, it produces following result −

List elements :  [123, 'xyz', 'zara', 'abc']

Example

We can also convert a string into a list where the characters in the string become separate elements of the list. If needed, the elements can be replaced or updated as the list is mutable. Let us see the example below.

aString = "hello"
aList = list(aString)
print("List elements : ", aList)

On executing the program above, the output is obtained as follows −

List elements :  ['h', 'e', 'l', 'l', 'o']

Example

In this example, we are creating a Python set with integer elements and using the list() method, let us try to convert a Python set into a Python list.

aSet = {1, 2, 3, 4, 5}
aList = list(aSet)
print("List elements : ", aList)

The output for the program above is displayed as follows −

List elements :  [1, 2, 3, 4, 5]

Example

As we discussed earlier, when a dictionary is converted into a list, only the key values are stored as elements of the list. The example demonstrating it is given below.

aDict = {1: "a", 2: "b", 3: "c", 4: "d", 5: "e"}
aList = list(aDict)
print("List elements : ", aList)

If we compile and run the program, and the result is produced as follows −

List elements :  [1, 2, 3, 4, 5]
python_lists.htm
Advertisements