Python’s list() Function

Learn Python @ Freshers.in

Python’s list() function is a powerful tool for creating lists from iterable objects. In this comprehensive guide, we’ll explore the intricacies of list(), covering its syntax, applications, and practical examples to help you leverage it effectively in Python programming.

Understanding list() Function:

The list() function in Python is used to create a list from an iterable object. Its syntax is straightforward:

list(iterable)

iterable: An iterable object (such as a string, tuple, set, etc.) whose elements will be used to create the list.

Example 1: Converting String to List

Let’s start with a simple example of converting a string to a list:

my_string = "Python"
my_list = list(my_string)
print(my_list)  # Output: ['P', 'y', 't', 'h', 'o', 'n']

Here, we use list() to convert the string "Python" into a list of characters.

Example 2: Converting Tuple to List

You can also convert a tuple to a list using list():

my_tuple = (1, 2, 3, 4, 5)
my_list = list(my_tuple)
print(my_list)  # Output: [1, 2, 3, 4, 5]

In this example, list() converts the tuple (1, 2, 3, 4, 5) into a list with the same elements.

Example 3: Creating Empty List

list() can also be used to create an empty list:

empty_list = list()
print(empty_list)  # Output: []

Here, list() creates an empty list, which is represented by [].

Example 4: Converting Set to List

You can convert a set to a list as well:

my_set = {1, 2, 3, 4, 5}
my_list = list(my_set)
print(my_list)  # Output: [1, 2, 3, 4, 5]

In this example, list() converts the set {1, 2, 3, 4, 5} into a list with the same elements.

Example 5: Using list() with Range

list() can also be used with the range() function to create a list of numbers:

my_range = range(1, 6)
my_list = list(my_range)
print(my_list)  # Output: [1, 2, 3, 4, 5]

Here, list() converts the range object range(1, 6) into a list of numbers from 1 to 5.

Author: user