Python list() Function



The Python list() function is used to create a new list. A list is a collection of items that can hold different types of data, such as numbers, strings, or other objects. It is an ordered and mutable (changeable) data structure, allowing you to store and organize multiple values in a single variable.

Lists are defined by square brackets [], and the individual items inside the list are separated by commas. You can access elements within a list using their index (position), with the first element at index 0.

Syntax

Following is the syntax of Python list() function −

list(iterable)

Parameters

This function accepts any iterable object like a string, tuple, set, or another list as a parameter.

Return Value

This function returns a new list object with the elements from the given iterable.

Example

In the following example, we are using the list() function to convert the string "Hello" into a list of its individual characters −

my_string = "Hello"
string_list = list(my_string)
print('The list object obtained is:',string_list)

Output

Following is the output of the above code −

The list object obtained is: ['H', 'e', 'l', 'l', 'o']

Example

Here, we are using the list() function to convert the tuple "(1, 2, 3)" into a list −

my_tuple = (1, 2, 3)
tuple_list = list(my_tuple)
print('The list object obtained is:',tuple_list)

Output

Output of the above code is as follows −

The list object obtained is: [1, 2, 3]

Example

In here, we are using the list() function without any arguments, creating an empty list ([]) −

empty_list = list()
print('The list object obtained is:',empty_list)

Output

The result obtained is as shown below −

The list object obtained is: []

Example

In this case, we convert the elements of the set "{4, 5, 6}" into a list −

my_set = {4, 5, 6}
set_list = list(my_set)
print('The list object obtained is:',set_list)

Output

Following is the output of the above code −

The list object obtained is: [4, 5, 6]

Example

In this example, we apply the list() function to a range object representing the range from 1 to 4 −

range_list = list(range(1, 5))
print('The list object obtained is:',range_list)

Output

The result produced is as follows −

The list object obtained is: [1, 2, 3, 4]
python-list-function.htm
Advertisements