List
Lists are just like dynamically sized arrays, declared in other languages. A list is a collection of things, created using [ ] and separated by commas.
Var = ["Liberation", "By", "Education"]
print(Var)
['Liberation', 'By', 'Education']
Lists are the simplest containers that are an integral part of the Python language. Lists need not be homogeneous always which makes it the most powerful tool in Python. A single list may contain data types like integers, strings, as well as objects. List is a collection which is ordered and mutable. Allows duplicate members. Lists are mutable, and hence, they can be altered even after their creation.
Creating a list in Python: Lists in Python can be created by just placing the sequence inside the square brackets [ ]. Unlike sets, a list doesn't need a built-in function for its creation of a list.
Example:
# Creating a List
List = []
print("Blank List: ")
print(List)
# Creating a List of numbers
List = [10, 20, 30]
print("\nList of numbers: ")
print(List)
# Creating a List of strings and accessing using index
List = ["LIBED", "PYTHON", "TUTORIAL"]
print("\nList Items: ")
print(List[0])
print(List[2])
Output:
Blank List:
[]
List of numbers:
[10, 20, 30]
List Items:
LIBED
TUTORIAL
Creating a list with multiple distinct or duplicate elements: A list may contain duplicate values with their distinct positions and hence, multiple distinct or duplicate values can be passed as a sequence at the time of list creation.
Example:
# Creating a List with the use of Numbers (Having duplicate values)
List = [1, 2, 4, 4, 3, 3, 3, 6, 5]
print("List with the use of Numbers: ", List)
# Creating a List with mixed type of values (Having numbers and strings)
List = [1, 2, 'Libed', 4, 'Python', 6, 'Tutorial']
print("\nList with the use of Mixed Values: ")
print(List)
Output:
List with the use of Numbers: [1, 2, 4, 4, 3, 3, 3, 6, 5]
List with the use of Mixed Values:
[1, 2, 'Libed', 4, 'python', 6, 'Tutorial']
Size of Python list: Python len() is used to get the length of the list.
Example:
# Creating a List
List1 = []
print(len(List1))
# Creating a List of numbers
List2 = [10, 20, 14]
print(len(List2))
Output:
0
3
Accessing elements from the List: In order to access the list items refer to the index number. Use the index operator [ ] to access an item in a list. The index must be an integer. Nested lists are accessed using nested indexing.
Example:
# accessing a element from the list using index number
List = ["Libed", "Python", "Tutorial"]
print("Accessing a element from the list")
print(List[0])
print(List[2])
Output:
Accessing a element from the list
Libed
Tutorial
Accessing elements from a multi-dimensional list: We can also access the elements in a multidimensional list using rows and columns.
Example:
# Creating a Multi-Dimensional List
List = [['LIBED', 'TUTORIAL'], ['PYTHON']]
# Accessing an element from the Multi-Dimensional List using index number
print("Accessing a element from a Multi-Dimensional list")
print(List[0][1])
print(List[1][0])
Output:
Accessing a element from a Multi-Dimensional list
TUTORIAL
PYTHON
List Slicing: In Python, list slicing is the mostly used technique for programmers to solve efficient problems. In-order to access a range of elements in a list, list slicing is useful. Slicing can be performed by using the simple slicing operator colon(:). This operator will specify where to start the slicing, where to end, and specify the step.
List slicing returns a new list from the existing list. The Syntax of list slicing is Lst[Initial : End : IndexJump]. If Lst is a list, then the above expression returns the portion of the list from index initial to end, at a step size IndexJump. Slice operation is performed on Lists with the use of a colon(:).
- To print elements from beginning to a range use:
[: Index] - To print elements of a list with skip count:
[::2] - To print elements from end use:
[:-Index] - To print the whole list in reverse order, use:
[::-1] - To print elements from a specific Index till the end use:
[Index:]
Example:
my_list = [50, 70, 30, 20, 90, 10, 50]
# Display list
print(my_list[::])
# slice first four items
print(my_list[:4])
# print every second element with a skip count 2
print(my_list[::2])
# reversing the list
print(my_list[::-1])
# Without end_value Stating from 3nd item to last item
print(my_list[3:])
Output:
[50, 70, 30, 20, 90, 10, 50]
[50, 70, 30, 20]
[50, 30, 90, 50]
[50, 10, 90, 20, 30, 70, 50]
[20, 90, 10, 50]
List Methods
Python has a set of built-in methods that you can use on lists/arrays. Python does not have built-in support for Arrays, but in Python Lists can be used instead.
Below are few common list methods:
append()
Elements can be added to the List by using the built-in append() function. Only one element at a time can be added to the list by using the append() method, for the addition of multiple elements with the append() method, loops are used. Tuples can also be added to the list with the use of the append method because tuples are immutable. Unlike Sets, Lists can also be added to the existing list with the use of the append() method.
Example:
# Addition of elements in a List
List = []
print("Initial blank List: ", List)
# Addition of Elements in the List
List.append(1)
List.append(2)
List.append(3)
print("\nList after Addition of Three elements: ", List)
Output:
Initial blank List: []
List after Addition of Three elements: [1, 2, 3]
clear()
clear() method is used for removing all items from the List. The list clear() method modifies the list in-place, i.e. it doesn't create any copy of the list.
Syntax is list.clear().
The clear() method doesn't take any parameters. List clear() method doesn't return any value.
Example:
# Remove all elements from the fruits list.
fruits = ['apple', 'banana', 'cherry', 'orange']
fruits.clear()
print(fruits)
Output:
[]
count()
List count() method returns the count of how many times a given object occurs in a List.
Syntax is list_name.count(object).
The parameter object is the item whose count is to be returned. Returns the count of how many times an object occurs in the list.
Example:
# list count
my_list = ['a', 'a', 'a', 'b', 'b', 'a', 'c', 'b']
print(my_list.count('b'))
Output:
3
extend()
Other than append() and insert() methods, there's one more method for the Addition of elements, extend(), this method is used to add multiple elements at the same time at the end of the list.
Example:
# Addition of elements in a List using Extend Method
List = [1, 2, 3, 4]
print("Initial List: ", List)
# Addition of multiple elements to the List at the end
List.extend([8, "Python", "Tutorial"])
print("\nList after performing Extend Operation: ")
print(List)
Output:
Initial List: [1, 2, 3, 4]
List after performing Extend Operation:
[1, 2, 3, 4, 8, 'Python', 'Tutorial']
insert()
The append() method only works for the addition of elements at the end of the List, for the addition of elements at the desired position, insert() method is used. Unlike append() which takes only one argument, the insert() method requires two arguments(position, value).
Example:
# Addition of elements in a List
List = [1, 2, 3, 4]
print("Initial List: ", List)
# Addition of Element at specific Position
List.insert(3, 12)
List.insert(0, 'LIBED')
print("\nList after performing Insert Operation: ")
print(List)
Output:
Initial List: [1, 2, 3, 4]
List after performing Insert Operation:
['LIBED', 1, 2, 3, 12, 4]
sort()
Python list sort() function can be used to sort a List in ascending, descending, or user-defined order. The sort() method will sort the list alphanumerically. In each case, the time complexity is O(nlogn) in Python.
Syntax is List_name.sort(reverse=True/False, key=myFunc).
The parameters are:
reverse(Optional) —reverse=Truewill sort the list descending. Default isreverse=False.key(Optional) — A function to specify the sorting criteria(s).
Example:
List1 = [100, 50, 65, 82, 23]
List1.sort()
print(List1)
List2 = ["orange", "mango", "kiwi", "pineapple", "banana"]
List2.sort()
print(List2)
List2.sort(reverse=True)
print(List2)
Output:
[23, 50, 65, 82, 100]
['banana', 'kiwi', 'mango', 'orange', 'pineapple']
['pineapple', 'orange', 'mango', 'kiwi', 'banana']