lettura simple

The list() Function in Python

The list() function is our handy tool that brings a new list to life from a sequence of elements.

list(x)

In this case, x is a sequence of elements, such as a tuple, a string, etc.

The function creates and returns a list consisting of the elements you specify.

Quick tip. This handy function is quite versatile. You can use it to whip up a list, an empty list, or even morph other data sequences into a list.

Let's dive into some practical examples.

Creating an Empty List

Creating an empty list is a cinch. Just don't include any elements in those round brackets.

my_list = list()

The list() function generates a new empty list, that is, a list devoid of any elements.

[ ].

Converting a String to a List

If you feed a string into the list() function, it cleverly crafts a list containing each character from your string.

my_list = list("Hello")

Think of it like this: each item in the list is a unique character from your string.

['H', 'e', 'l', 'l', 'o'].

Converting a Tuple to a List

Your starting sequence of elements could also be a tuple.

If you give the list() function a tuple, it transforms the tuple into a list.

my_tuple = (1, 2, 3, 4, 5)
my_list = list(my_tuple)

The result? You've got a list packed with the same elements as your tuple.

[1, 2, 3, 4, 5].

Creating a List from a Numeric Range

You can also create a list by specifying a numeric range.

my_list = list(range(1, 6))

The list function gets to work and presents a new list with integers from 1 through to 5.

[1, 2, 3, 4, 5].

And there you have it, just a few practical ways to use the list() method to create lists in Python. It's a wonderful tool, don't you think?




Report a mistake or post a question




FacebookTwitterLinkedinLinkedin