Table of Contents
ToggleIntroduction
The list() function in Python is used to create new lists from existing iterables like strings, tuples, dictionaries etc. The list type is one of the most commonly used data structures in Python.
Brief Overview Of List Function Python
- list() is a built-in function in Python to create new list objects.
- It converts various data types like strings, tuples, dictionaries to lists.
- list() can also create lists with repeated elements and accept multiple input arguments.
- Understanding list() is important as lists are used extensively in Python programming.
Importance Of List Function Python
Some key reasons why the list() function is important:
- Creating and manipulating lists is essential in Python. list() provides a simple way to make new lists.
- It is handy to quickly convert other data types like strings and tuples into lists for processing.
- list() accepts iterables as input, so you can easily make lists from tuples, sets, dictionaries.
- It has several useful parameters to customise creation of new lists.
- Lists are mutable unlike strings and tuples. So list() allows making mutable copies.
Types of list function Python
The list() function in python can be used in different ways:
Default list
You can call list() without any arguments to make an empty list:
// Creating default list in python empty_list = list() print(empty_list) # []
List from Iterable
Pass an iterable like string, tuple etc. to convert them to lists:
// Creating List from Iterables in python string = "python" list_from_string = list(string) print(list_from_string) # ['p', 'y', 't', 'h', 'o', 'n']
This repeats those three arguments to create the list.
Syntax of the list() Function
The standard syntax of list() is:
// Syntax of the list Function Python list([iterable])
iterable (optional): Any iterable object like string, tuple, set, dictionary etc. whose elements can be looped over.
Some examples:
// Syntax of the list Function Python list('hello') list((1,2,3)) list({1, 2, 3}) list(['a', 'b', 'c']) list(range(3))
All of these will create a new list from the given iterable.
Parameters Explained
list() doesn’t have any required parameters. The optional parameters are:
iterable (optional): The iterable object to be converted into list. Can be string, tuple, set, dictionary etc. If not passed, an empty list is created.
For example:
// Parameters in List function python list("python") # ['p', 'y', 't', 'h', 'o', 'n'] list() # [] (empty list)
Understanding the Return Value
The list() functions returns a new list object after converting the given arguments.
For example:
// Return Value in List function python fruits = ('apple', 'banana', 'mango') fruits_list = list(fruits) print(type(fruits_list)) # <class 'list'>
The return type will be a list. If no args are passed, it returns an empty list [].
Operations Using the list() Function
We can perform all the regular list operations like adding, removing, sorting etc. on lists created with list():
Operation | Description | Example |
---|---|---|
len(list) | Returns length of list | len([1, 2, 3]) -> 3 |
list[i] | Accesses element at index i | list[0], list[-1] |
list[i:j] | Slice from index i to j | list[1:3] -> [2, 3] |
list.append(x) | Appends x to end of list | list.append(4) |
list.insert(i, x) | Inserts x at index i | list.insert(2, 5) |
list.remove(x) | Removes first occurrence of x | list.remove(3) |
list.pop(i) | Removes & returns element at i | list.pop(), list.pop(0) |
list.clear() | Removes all elements | list.clear() |
list.index(x) | Returns index of first x | list.index(3) -> 2 |
list.count(x) | Counts occurrences of x | list.count(2) -> 1 |
list.sort() | Sorts elements in place | list.sort() |
list.reverse() | Reverses list in place | list.reverse() |
list1 + list2 | Concatenates lists | [1,2] + [3,4] -> [1,2,3,4] |
Let’s look into some of these operations in detail
Adding Elements
Use append(), extend() or insert() to add elements:
- append() – Adds an element to the end of the list.
- extend() – Extends the list by appending elements from another iterable.
- insert() – Inserts an element at the given index, shifting elements after it to the right.
// Adding Element in list python nums = list(range(3)) # [0, 1, 2] nums.append(3) nums.extend([4,5]) nums.insert(2, 10) print(nums) # [0, 1, 10, 2, 3, 4, 5]
Removing Elements
Use remove(), pop() or clear() to remove elements:
- remove(): Removes the first matching element from the list.
- pop(): Removes and returns the element at the given index (last index by default).
- clear(): Removes all elements from the list, making it empty.
// Removing Element in list python fruits = list(('apple', 'mango', 'grapes')) fruits.remove('mango') fruits.pop(1) fruits.clear()
Searching and Counting
Use index() to find index of first match. Use count() to count frequency of element.
// Searching And Counting in python list names = list(['John', 'Ravi', 'Ravi', 'Amy']) print(names.index('Ravi')) # 1 print(names.count('Ravi')) # 2
Sorting and Reversing
Use sort() to sort the list and reverse() to reverse order:
// Sorting and Reversing in python list nums = list([5, 2, 7, 3, 1]) nums.sort() nums.reverse() print(nums) # [7, 5, 3, 2, 1]
Slicing and Concatenation
We can slice sub-lists or concatenate lists:
// Slicing and Concatenation in python list letters = list('python') print(letters[2:4]) # ['t', 'h'] list1 = [1, 2] list2 = [3, 4] print(list1 + list2) # [1, 2, 3, 4]
So list() allows you to leverage full power of lists!
Applications and Use Cases
Some examples where list() can be used:
- Converting tuples, sets and dictionaries to lists since lists are mutable.
- Repeating a set of elements to multiple list items using the repeat parameter.
- Splitting strings into list of substrings for easier processing.
- Passing list as argument to functions that require iterable objets like sort(), min(), max() etc.
- Using list comprehension on lists constructed with list().
Best Practices for Using List Function Python
Some best practices for using list():
- Specify the iterable object explicitly instead of relying on automatic conversion.
- Avoid using list() on extremely large iterables as it creates unnecessary temporary objects.
- Consider alternatives like tuples if the sequence will not change after creation.
- Use list comprehensions instead of list() to construct lists using an expression.
- Do not pass multiple arguments to repeat elements when order doesn’t matter.
Conclusion
To summarize, list() is a versatile built-in function to create mutable lists in Python. It converts iterables into lists and allows repeating elements. Lists are core data structures integral to Python programming. The list() function supplements their usage with an easy way to construct list objects from other data types.
Try out our free resume checker service where our Industry Experts will help you by providing resume score based on the key criteria that recruiters and hiring managers are looking for.
FAQ Related To List Function Python
How is list() different from []?
A: The [] syntax creates an empty list directly, while list() calls the list class to create a list object. However, they are mostly interchangeable. Key differences are:
- list() can convert iterables to lists, [] cannot.
- list() can repeat elements, [] cannot.
What happens if no args are passed to list()?
A: If no iterable object is passed, list() simply creates and returns an empty list.
Can lists have mixed data types?
A: Yes, Python lists are heterogeneous and can have values of different data types like integers, strings etc.
Is list() faster than []?
A: No, both list() and [] have similar speeds. [] directly creates list, while list() calls the list constructor. But the speed difference is negligible.