Tutorial Study Image

Python list()

The list() function helps to returns a list object in Python. List in python are ordered and have a precise count. The list components are indexed and therefore the index starts with zero.


list([iterable]) # object can be string,sets,tuples,dictionary etc

list() Parameters:

Takes only one parameter. In this the sequence can be strings, tuples and collection can be set, dictionary.

Parameter Description Required / Optional
iterable  an object that could be a sequence or collection  or any iterator object Optional

list() Return Value

It returns a list and has only one parameter.

Input Return Value
 no parameters empty list
iterable is passed a list consisting of iterable's items

Examples of list() method in Python

Example 1: Create lists from string, tuple, and list


# empty list
print(list())

# vowel string
vowel_string = 'aeiou'
print(list(vowel_string))

# vowel tuple
vowel_tuple = ('a', 'e', 'i', 'o', 'u')
print(list(vowel_tuple))

# vowel list
vowel_list = ['a', 'e', 'i', 'o', 'u']
print(list(vowel_list))
 

Output:

[]
['a', 'e', 'i', 'o', 'u']
['a', 'e', 'i', 'o', 'u']
['a', 'e', 'i', 'o', 'u']

Example 2: Create lists from set and dictionary


# vowel set
vowel_set = {'a', 'e', 'i', 'o', 'u'}
print(list(vowel_set))

# vowel dictionary vowel_dicti 1, 'e': 2, 'i': 3, 'o':4, 'u':5}
print(list(vowel_dictionary))
 

Output:

['a', 'o', 'u', 'e', 'i']
['o', 'e', 'a', 'u', 'i']

Example 3: Create a list from an iterator object


# objects of this class are iterators
class PowTwo:
    def __init__(self, max):
        self.max = max
    
    def __iter__(self):
        self.num = 0
        return self
        
    def __next__(self):
        if(self.num >= self.max):
            raise StopIteration
        result = 2 ** self.num
        self.num += 1
        return result

pow_two = PowTwo(5)
pow_two_iter = iter(pow_two)

print(list(pow_two_iter))
 

Output:

[1, 2, 4, 8, 16]