WHAT IS LIST IN PYTHON?

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.MethodDescription-Code-Output
1append()#Adds an element at the end of the list
fruits = [โ€˜appleโ€™, โ€˜bananaโ€™, โ€˜cherryโ€™]
fruits.append(โ€œorangeโ€)
print(fruits)
#Output-[โ€˜appleโ€™, โ€˜bananaโ€™, โ€˜cherryโ€™, โ€˜orangeโ€™]
2clear()#Removes all the elements from the list
fruits = [โ€œappleโ€, โ€œbananaโ€, โ€œcherryโ€]
fruits.clear()
print(fruits)
#output- [ ]
3copy()#Returns a copy of the list
fruits = [โ€œappleโ€, โ€œbananaโ€, โ€œcherryโ€]
mylist = fruits.copy()
print(mylist)
#output-[โ€˜appleโ€™, โ€˜bananaโ€™, โ€˜cherryโ€™]
4count()#Returns the number of elements with the specified value
fruits = [โ€˜appleโ€™, โ€˜bananaโ€™, โ€˜cherryโ€™]
x = fruits.count(โ€œcherryโ€)
print(x)
#output- 1
5extend()#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]
6index()#Returns the index of the first element with the specified value
fruits = [โ€˜appleโ€™, โ€˜bananaโ€™, โ€˜cherryโ€™]
x = fruits.index(โ€œcherryโ€)
print(fruits)
#output- 2
7insert()#Adds an element at the specified position
fruits = [โ€œappleโ€, โ€œbananaโ€, โ€œcherryโ€]
fruits.insert(2, โ€œmangoโ€)
print(fruits)
#output-[โ€˜appleโ€™, โ€˜bananaโ€™, โ€˜mangoโ€™, โ€˜cherryโ€™]
8pop()#Removes the element at the specified position
fruits = [โ€œappleโ€,โ€bananaโ€,โ€cherryโ€]
fruits.pop(2)
print(fruits)
#output- [โ€˜appleโ€™, โ€˜bananaโ€™]
9remove()#Removes the item with the specified value
fruits = [โ€œappleโ€,โ€bananaโ€,โ€cherryโ€]
fruits.remove(โ€œbananaโ€)
print(fruits)
#output-[โ€˜appleโ€™, โ€˜cherryโ€™]
10reverse()#Reverses the order of the list
fruits = [โ€œbananaโ€, โ€œOrangeโ€, โ€œKiwiโ€, โ€œcherryโ€]
fruits.reverse()
print(fruits)
#output-[โ€˜cherryโ€™, โ€˜Kiwiโ€™, โ€˜Orangeโ€™, โ€˜bananaโ€™]
11sort()#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โ€™]

Python Lists Methods


Posted

in

Tags:

Comments

Leave a Reply