Python list() Function – Tutorial with Examples

The list() function in Python is a built-in function that creates a list from an iterable object. An iterable object is any object capable of returning its elements one at a time. Examples of iterable objects include lists, strings, dictionaries, and sets.

Syntax

list(iterable)

Parameters

iterable – an iterable object (such as a list, string, tuple, set, or dictionary).

Return Value

The list() function returns a list object, which is a collection of ordered, mutable, and indexed elements.

Examples

Example 1: Creating a list from a string

string = "Hello World"
result = list(string)
print(result)

Output:

['H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd']

In this example, we have defined a string, string, which contains the words “Hello World”. The list() function is then used to create a list from the string, by passing the string as an argument to the function. The resulting list contains the individual characters of the string as its elements.

Example 2: Creating a list from a tuple

tuple = (1, 2, 3, 4)
result = list(tuple)
print(result)

Output:

[1, 2, 3, 4]

In this example, we have defined a tuple, tuple, which contains the numbers 1, 2, 3, and 4. The list() function is then used to create a list from the tuple, by passing the tuple as an argument to the function. The resulting list contains the elements of the tuple in the same order as the original tuple.

Example 3: Creating a list from a set

set = {1, 2, 3, 4}
result = list(set)
print(result)

Output:

[1, 2, 3, 4]

In this example, we have defined a set, set, which contains the numbers 1, 2, 3, and 4. The list() function is then used to create a list from the set, by passing the set as an argument to the function. The resulting list contains the elements of the set in an arbitrary order, as sets are unordered collections.

Use Cases

The list() function is commonly used to:

  • Convert an iterable object into a list for easier manipulation and iteration.
  • Combine multiple iterable objects into a single list.
  • Create a list of characters from a string for processing and manipulation.
  • Convert a tuple or set into a list for modifying the elements.
  • Easily convert an iterable object into a list for use in other operations or functions that require a list as an input.

In summary, the list() function is a versatile and useful tool for converting and manipulating iterable objects in Python. It provides a convenient way to convert objects into lists and can be used in a variety of different contexts and applications.

Leave a Reply

Your email address will not be published. Required fields are marked *