GtR
GtR

Reputation: 13

List Constructor: How does it really work in the following code?

thislist = list(("apple", "banana", "cherry"))
thislist = ["apple", "banana", "cherry"]

In terms of

I would like to understand how exactly does the above code function and create the list.

Upvotes: 0

Views: 1066

Answers (3)

Anidhya Bhatnagar
Anidhya Bhatnagar

Reputation: 646

list and tuple are both built in python classes.

Let's first talk about Lists

Lists are sequences and are used to store collections of homogeneous items.

The list constructor is:

list([iterable])

You can construct List in several ways:

  • With a pair of square brackets which denotes the empty list. For Example: []
  • With square brackets and items separated with commas. For Example: [a, b, c]
  • With the help of a list comprehension. For Example: [x for x in iterable]
  • With the help of type constructor. For Example: list() or list(iterable)

The constructor list(iterable) builds a list whose items are the same and in the same order as iterable’s items.

Here, iterable may be either a sequence or an object that supports iteration, or an iterator object.

If iterable is already a list: A copy of the list is returned

For example:

>>> list('abc') 
['a', 'b', 'c'] 
>>> list( (1, 2, 3) ) # Next let's understand what a tuple is
[1, 2, 3]

Now let's talk about Tuples

Tuples are sequences which are used to store collections of heterogeneous data.

The tuple constructor is:

tuple([iterable])

You can create tuples in many ways:

  • With a pair of parentheses to denote the empty tuple. For Example: ()
  • With many items separated by commas. For Example: (a, b, c)
  • With a trailing comma for a singleton tuple. For Example: a, or (a,)
  • With the help of tuple() constructor. For Example: tuple() or tuple(iterable)

This tuple(iterable) constructor builds a tuple with identical items and in same order as iterable’s items. The iterable can be a sequence or an iterator object.

If iterable is already a tuple it's copy will be returned. For Example:

>>> tuple('abc') 
('a', 'b', 'c') 
>>> tuple( [1, 2, 3] ) 
(1, 2, 3)
>>> tuple
()
>>> t = 1,2,3
>>> t
(1, 2, 3)

Note that it is actually the comma which makes a tuple, not the parentheses. The parentheses are optional, except in the empty tuple case, or when they are needed to avoid syntactic ambiguity.

Taking your question as an example:

You want to give a tuple to create a list. So to identify that the input to the list constructor is a tuple it is need to be enclosed in parentheses.

thislist = list(("apple", "banana", "cherry"))

Here ("apple", "banana", "cherry") will create a tuple implicitly. Then this tuple ("apple", "banana", "cherry") is the iterable input for the list constructor and returns an list object.

>>> type(("apple", "banana", "cherry"))
<class 'tuple'>

When you provide ["apple", "banana", "cherry"], an object of list is created implicitly and returned.

>>> type(["apple", "banana", "cherry"])
<class 'list'>

Upvotes: 0

Mad Physicist
Mad Physicist

Reputation: 114440

list is a built-in class in Python. There are three main ways of constructing a list.

The first way is by calling the "constructor", or list.__call__, usually with list(...). The constructor accepts any iterable and initializes a list that refers to all of its elements. In your first example, you pass in the tuple of strings ("apple", "banana", "cherry"). The result of the assignment is that a new list object is bound to the name thislist.

The second way is by enclosing a comma-separated collection in square brackets. The result of thislist = ["apple", "banana", "cherry"] is that a new list object equal to the one in the first example is bound to the name thislist. This notation is possible because the type list is so integral to the Python language that the interpreter recognizes this syntax. Other examples of similarly fundamental data structure types are set (initialized by {'a', 'b', 'c'}), dict (initialized by {'a': 1, 'b': 2, 'c': 3}) and tuple (initialized by ('a', 'b', 'c')).

The third way to construct a list is through a comprehension. It's sort of a hybrid of the first two ways because it allows you to use an iterable, rather than a literal sequence, inside square brackets. An example of a list comprehension would be something like:

thislist = [x for x in ("apple", "banana", "cherry")]

In general, a comprehension works by constructing an empty list and appending the elements of the generator expression in the brackets. It's roughly equivalent to

thislist = []  # or thislist = list()
for x in ("apple", "banana", "cherry"):
    thislist.append(x)

Upvotes: 1

Shubham Paliwal
Shubham Paliwal

Reputation: 101

List is a built-in python iterator:

This will initiate a new empty list:

this_list = list() -> this_list is now a list object

This will create a new list initialized from iterable's items

this_list = list(iterable) -> List 'this_list' is being constructed using list constructor

For ex:

this_tuple = ("apple", "banana", "cherry")

To convert this tuple into list one would use:

>>> this_list = list(this_tuple)

>>> this_list

["apple", "banana", "cherry"]

Upvotes: 0

Related Questions