LIST DEFINITION-
A LIST is basically a data structure consisting of a collection of any datatype ordered, changeable, and indexed elements or items, created by enclosing elements in square brackets or by using List() constructor. List items allow duplicate values and its first item has index [0].
Properties of List items-
Ordered– List items have a defined order, and that order will not change. If we add new items to a list, the new items will be placed at the end of the list.
Changeable or Mutable– We can change, add, and remove items in a list.
Allow Duplicates– Since lists are indexed, lists can have items with the same value.
Python code
thislist = ["apple", "banana", "cherry", "apple", "cherry"]
print(thislist)
Output
['apple', 'banana', 'cherry', 'apple', 'cherry']
Any Datatype-List items can be of any data type.
A list with strings, integers, and boolean values-
list1 = ["abc", 34, True, 40, "male"]
How to create a list in python?
Creating a List by using square brackets []
Python Code
fruits = ["apple", "banana", "cherry"]
print(fruits)
Output
['apple', 'banana', 'cherry']
Creating a List by using the list() Constructor
Python Code
fruits = list(("apple", "banana", "cherry"))
print(fruits)
Output
['apple', 'banana', 'cherry']
How to access items of Python lists?
List items are indexed and we can access them by referring to the index number. The first item of a list has an index 0. Negative indexing means start from the end as -1 refers to the last item, -2 refers to the second last item etc.
Python code
fruits = ["apple", "banana", "cherry"]
print(fruits[-1],fruits[0])
Output
cherry apple
Using Range of Indexes
We can access items of a list as a new list containing items accessed by specifying the start and end range as shown below
Python Code
fruits = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]
print(fruits[1:3])
This will return the items from position 1 to 3, first item is having position 0, and item in position 3 is not included
Output
['banana', 'cherry']
Using Range of Negative Indexes
To access the items from the end of the list we need to provide a negative range. The result will include items available at index value from the start of range value and one less than the end of range value.
This example returns the items from “kiwi” (-3) to, but not including “mango” (-1)
Python Code
fruits = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]
print(fruits[-3:-1])
Output
['kiwi', 'melon']
Using in keyword
Python Code
fruits = ["apple", "banana", "cherry"]
print("banana" in fruits)
Output
True
How to change the items of the list in Python?
We can change the value of items by referring to their index number as shown below
Python Code
fruits = ["apple", "banana", "cherry"]
fruits[2] = "blackcurrant"
print(fruits)
It will change the third item value
Output
['apple', 'banana', 'blackcurrant']
Changing a Range of Item Values in Python Lists
We can change the value of items within a specific range, by defining a list with the new values and referring to the range of index numbers where we want to insert the new values.
Python code
fruits = ["apple", "banana", "cherry", "orange", "kiwi", "mango"]
fruits[1:3] = ["strawberry", "papaya"]
print(fruits)
It will change values in the list from, banana to strawberry and cherry to papaya.
Output
['apple', 'strawberry', 'papaya', 'orange', 'kiwi', 'mango']
If we insert more items than we replace, the new items will be inserted where we specified, and the remaining items will move accordingly:
Python code
fruits = ["apple", "banana", "cherry", "orange", "kiwi", "mango"]
fruits[1:2] = ["strawberry", "papaya"]
print(fruits)
Output
['apple', 'strawberry', 'papaya', 'cherry', 'orange', 'kiwi', 'mango']
If we insert less items than we replace, the new items will be inserted where we specified, and the remaining items will move accordingly as shown in below example
Python code
fruits = ["apple", "banana", "cherry"]
fruits[1:3] = ["mango"]
print(fruits)
Output
['apple', 'mango']
How to ADD items to the list?
We can add items to the list by-
Using the insert() method in Python List
The insert() method inserts an item at the specified index by
Python code
fruits = ["apple", "banana", "cherry"]
fruits.insert(2, "mango")
print(fruits)
Output
['apple', 'banana', 'mango', 'cherry']
Using the append() method in Python Lists
append() method add an item to the end of list as shown below
Python code
fruits = ["apple", "banana", "cherry"]
fruits.append("orange")
print(fruits)
Output
['apple', 'banana', 'cherry', 'orange']
Using the extend() method in Python Lists
The extend() method can add any iterable object (lists, tuples, sets, dictionaries, etc.).
The extend() method append elements from another list to the current list as shown below-
Python code
fruits1 = ["apple","banana","cherry"]
fruits2 = ["mango","pineapple","papaya"]
fruits1.extend(fruits2)
print(fruits1)
Output
['apple', 'banana', 'cherry', 'mango', 'pineapple', 'papaya']
How to remove items from the list?
Using the remove() method in Python Lists
The remove() method removes the specified item.
Python code to remove items from the list-
fruits = ["apple","banana","cherry"]
fruits.remove("banana")
print(fruits)
Output
['apple', 'cherry']
Using the pop() method in Python Lists
The pop() method removes the item at the specified index. If we do not specify the index, the pop() method removes the last item.
Python code to remove the item at the specified index from the Python list
fruits = ["apple","banana","cherry"]
fruits.pop(2)
print(fruits)
Output
['apple', 'banana']
Using the del keyword in Python Lists
The del keyword also removes the item at the specified index:
Python code to remove the item at the specified index from the Python list
fruits = ["apple","banana","cherry"]
del fruits[0]
print(fruits)
Output
['banana', 'cherry']
The del keyword can also be used to delete the list completely.
Python code to delete the list completely
fruits = ["apple", "banana", "cherry"]
del fruits
To check the deleted list print the list fruits, and the output will be an error message.
print(fruits) #output will be an error message
Using the clear() method in the Python Lists
The clear() method empties the List.
The list will not be deleted, only its content gets deleted. The output will be an empty list.
Python code to clear the content of the Python List
fruits = ["apple", "banana", "cherry"]
fruits.clear()
print(fruits)
Output
[]
How to use a loop in Python lists?
Using for loop in the Python Lists
Python code to print each item one by one using the for loop in the Python list
fruits = ["apple", "banana", "cherry"]
for x in fruits:
print(x)
Output
apple
banana
cherry
We can also loop through the list items by referring to their index number. The range() and len() methods are used in for loop. The len() method will return the no. of items available in the loop and the range() method will return the range over which iteration is applied, it starts from 0 and end at one less than the input argument. The range() method in the following example creates the iterable [0,1,2].
fruits = ["apple", "banana", "cherry"]
for i in range(len(fruits)):
print(fruits[i])
Output
apple
banana
cherry
Using the while loop in the Python Lists
We will use the len() method to get the length of the list, then start at 0 and loop our way through the list items by referring to their indexes. We will increase the index by 1 after each iteration.
Python code to print each item one by one using the while loop in the Python list
fruits = ["apple", "banana", "cherry"]
i = 0
while i < len(fruits):
print(fruits[i])
i = i + 1
Output
apple
banana
cherry
Using List Comprehension in the Python Lists
List Comprehension is used to shorten the code for loops
fruits = ["apple", "banana", "cherry"]
[print(x) for x in fruits]
Output
apple
banana
cherry
We can create new list using List Comprehension
condition provided if “a” in x is optional.
fruits = ["apple", "banana", "cherry", "kiwi", "mango"]
newlist = [x for x in fruits if "a" in x]
print(newlist)
Output
['apple', 'banana', 'mango']
How to sort a Python List?
Using the sort() method in Python List
Ascending Sort
The sort() method sorts the list alphanumerically, ascending, by default
fruits = ["orange", "mango", "kiwi", "pineapple", "banana"]
fruits.sort()
print(fruits)
Output
['banana', 'kiwi', 'mango', 'orange', 'pineapple']
Descending Sort
The sort() method sorts the list alphanumerically, descending, by using the keyword argument reverse = True
fruits = ["orange", "mango", "kiwi", "pineapple", "banana"]
fruits.sort(reverse = True)
print(fruits)
Output
['pineapple', 'orange', 'mango', 'kiwi', 'banana']
Customize Sort Function
The sort() method sorts the list using customize function.
We can also customize our own function by using the keyword argument
key = function.
The function will return a number that will be used to sort the list (the lowest number first)
Python Code to Sort the list based on how close the number is to 40
def myfunc(n):
return abs(n - 40)
fruits = [80, 40, 55, 42, 43]
fruits.sort(key = myfunc)
print(fruits)
Output
[40, 42, 43, 55, 80]
Case Insensitive Sort
The sort() method is case-sensitive by default, resulting in all capital letters being sorted before lowercase letters.
For the case-insensitive sort function, use inbuilt str.lower as a key function
fruits = ["banana", "Orange", "Kiwi", "cherry"]
fruits.sort(key = str.lower)
print(fruits)
Output
['banana', 'cherry', 'Kiwi', 'Orange']
How to reverse the order of a Python List?
The reverse() method reverses the current sorting order of the elements of the list.
Using the reverse() method in the Python Lists
fruits = ["banana", "Orange", "Kiwi", "cherry"]
fruits.reverse()
print(fruits)
Output
['cherry', 'Kiwi', 'Orange', 'banana']
How to copy a list in the Python Lists?
Using the copy() method in the Python Lists
copy() method is an inbuilt method in Python that can be used to copy the list as shown in the below example
fruits = ["apple", "banana", "cherry"]
mylist = fruits.copy()
print(mylist)
Output
['apple', 'banana', 'cherry']
Using the list() method in the Python Lists
List() method is a constructor for list object as shown above in this article, same can be also used to copy the list as shown in below example-
fruits = ["apple", "banana", "cherry"]
mylist = list(fruits)
print(mylist)
Output
['apple', 'banana', 'cherry']
How to join Lists in Python?
Using the + operator to concatenate or join Python Lists
list1 = ["a", "b", "c", "d"]
list2 = [1, 2, 3, 4]
list3 = list1 + list2
print(list3)
Output
['a', 'b', 'c', 'd', 1, 2, 3, 4]
Using the append() method to concatenate or join Python Lists
list1 = ["a", "b", "c", "d"]
list2 = [1, 2, 3, 4]
for x in list2:
list1.append(x)
print(list1)
Output
['a', 'b', 'c', 'd', 1, 2, 3, 4]
Using the extend() method to concatenate or join Python Lists
list1 = ["a", "b", "c", "d"]
list2 = [1, 2, 3, 4]
list1.extend(list2)
print(list1)
Output
['a', 'b', 'c', 'd', 1, 2, 3, 4]
List of in-built List methods in the Python Lists
Summary of List Methods, most of the methods are explained above in this article
Sr. No. | Method | Description-Code-Output |
1 | append() | #Adds an element at the end of the list fruits = [‘apple’, ‘banana’, ‘cherry’] fruits.append(“orange”) print(fruits) #Output-[‘apple’, ‘banana’, ‘cherry’, ‘orange’] |
2 | clear() | #Removes all the elements from the list fruits = [“apple”, “banana”, “cherry”] fruits.clear() print(fruits) #output- [ ] |
3 | copy() | #Returns a copy of the list fruits = [“apple”, “banana”, “cherry”] mylist = fruits.copy() print(mylist) #output-[‘apple’, ‘banana’, ‘cherry’] |
4 | count() | #Returns the number of elements with the specified value fruits = [‘apple’, ‘banana’, ‘cherry’] x = fruits.count(“cherry”) print(x) #output- 1 |
5 | extend() | #Add the elements of a list (or iterable), to the end of the current list list1 = [“a”, “b”, “c”, “d”] list2 = [1, 2, 3, 4] list1.extend(list2) print(list1) #output-[‘a’, ‘b’, ‘c’, ‘d’, 1, 2, 3, 4] |
6 | index() | #Returns the index of the first element with the specified value fruits = [‘apple’, ‘banana’, ‘cherry’] x = fruits.index(“cherry”) print(fruits) #output- 2 |
7 | insert() | #Adds an element at the specified position fruits = [“apple”, “banana”, “cherry”] fruits.insert(2, “mango”) print(fruits) #output-[‘apple’, ‘banana’, ‘mango’, ‘cherry’] |
8 | pop() | #Removes the element at the specified position fruits = [“apple”,”banana”,”cherry”] fruits.pop(2) print(fruits) #output- [‘apple’, ‘banana’] |
9 | remove() | #Removes the item with the specified value fruits = [“apple”,”banana”,”cherry”] fruits.remove(“banana”) print(fruits) #output-[‘apple’, ‘cherry’] |
10 | reverse() | #Reverses the order of the list fruits = [“banana”, “Orange”, “Kiwi”, “cherry”] fruits.reverse() print(fruits) #output-[‘cherry’, ‘Kiwi’, ‘Orange’, ‘banana’] |
11 | sort() | #Sorts the list #syntax- list.sort(reverse=True|False, key=myFunc) fruits = [“orange”, “mango”, “kiwi”, “pineapple”, “banana”] fruits.sort() #sort in desc. order add argument reverse=True print(fruits) #output- [‘banana’, ‘kiwi’, ‘mango’, ‘orange’, ‘pineapple’] |