Python Lists

Table Of Contents:

  1. What Are Python Lists?
  2. Creating A List In Python.
  3. Accessing Elements From the List.
  4. Getting The Size Of The Python List.
  5. List Membership Check.
  6. Adding Elements To A Python List.
  7. Removing Elements From The List.
  8. Reversing A List.
  9. Sorting A List.
  10. Joining A Lists.
  11. Copying A Lists.
  12. Slicing A List.
  13. List Comprehension.

(1) What Are Python Lists?

  • Lists are used to store multiple items in a single variable.
  • Lists are created using square brackets [ ] and elements are separated using a comma ( , ).
  • Lists need not be homogeneous always which makes it the most powerful tool in Python.
  • A single list may contain DataTypes like Integers, Strings, as well as Objects.
  • Lists are mutable, and hence, they can be altered even after their creation.
  • Lists are ordered data structures, which means that the items have a defined order, and that order will not change.
  • If you add new items to a list, the new items will be placed at the end of the list.
  • The list can able to store duplicate values also.

(2) Creating A List In Python.

  • You can create a List by using square brackets [ ].
  • You can add multiple elements inside a list separated by a comma( , ).

Example

lst1 = [] #Empty List

lst2 = [1,2,3,4,5,6] #Numbered List

lst3 = ['a','b','c','d','e'] #Character List

lst4 = [1,'a',2,'b',3,'c',4,'d',5,'e',6] #Mixed List

lst5 = [1,3.141,'Hello',(4 + 6j)] #Mixed List

print(lst1)

print(lst2)

print(lst3)

print(lst4)

print(lst5)
Output:
[]
[1, 2, 3, 4, 5, 6]
['a', 'b', 'c', 'd', 'e']
[1, 'a', 2, 'b', 3, 'c', 4, 'd', 5, 'e', 6]
[1, 3.141, 'Hello', (4+6j)]

(3) Accessing Elements From The List

  • You can use the index of the list elements to access its values.
  • The index value starts with zero (0).

Example-1

lst = ['a','b','c','d','e']

print(lst[0])

print(lst[1])

print(lst[2])

print(lst[3])

print(lst[4])
Output:
a
b
c
d
e

Example-2

lst = ['a','b','c','d','e']

for i in lst:
    print(i)
Output:
a
b
c
d
e

(4) Getting Size Of The Python List

  • You can check how many elements are present inside a list using len() function.
  • It will return you the count of elements inside the list.

Example

lst = ['a','b','c','d','e']

print('Length: ',len(lst))
Output:
Length: 5

(5) List Membership Check

  • You can use ‘in’ or ‘not in’ operators to check whether a particular element is present inside a list or not.
  • ‘in’ – Returns True if the element is present inside a list.
  • ‘not in’ – Returns True if the element is not present inside the list.

Example- ‘in’ Operator

lst = ['a','b','c','d','e']

if 'd' in lst:
    print('d is present')
else:
    print('Not Present')
Output:
d is present

Example- ‘not in’ Operator

lst = ['a','b','c','d','e']

if 'g' not in lst:
    print('g is not present')
else:
    print('Present')
Output:
g is not present

(6) Adding Elements To A Python List

  • You can add new elements to an existing list.
  • You can use the below methods to add new elements to a list.
    (1) append()
    (2) insert()
    (3) extend()

(a) Using Append Method

  • append() method will add an element at the end of the list.
  • append() method can add only one element at a time, for the addition of multiple elements with the append() method, loops are used.
  • You can also add a list, tuple, set, or dictionary to an existing list.

Example-1: Adding Single Element

lst = [1,2,3,4,5,6]

print('Before: ',lst)

lst.append(7)

print('After: ',lst)
Output:
Before:  [1, 2, 3, 4, 5, 6]
After:  [1, 2, 3, 4, 5, 6, 7]

Example-2: Using for Loop

lst = [1,2,3,4,5,6]

print('Before: ',lst)

for i in range(7,11):
    lst.append(i)
    
print('After: ',lst)
Output:
Before:  [1, 2, 3, 4, 5, 6]
After:  [1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ]

Example-3: Adding Tuple To A List

lst = [1,2,3,4,5,6]

print('Before: ',lst)

lst.append((7,8,9,10))

print('After: ',lst)
Output:
Before:  [1, 2, 3, 4, 5, 6]
After:  [1, 2, 3, 4, 5, 6, (7, 8, 9, 10)]

Example-4: Adding List To A List

lst = [1,2,3,4,5,6]

print('Before: ',lst)

lst.append([7,8,9,10])

print('After: ',lst)
Output:
Before:  [1, 2, 3, 4, 5, 6]
After:  [1, 2, 3, 4, 5, 6, [7, 8, 9, 10]]

(b) Using Insert Method

  • insert() method is used to add an element at a specefic index position.
  • insert(position,value) methos takes two arguments,
  • Position: Index position where you want to add the element.
  • Value: Mention the value which you want to add.

Example-1

lst = [1,2,3,4,5]

print('Before: ',lst)

lst.insert(0,'Start')  #Inserting At The Start Index

print('After: ',lst)
Output:
Before:  [1, 2, 3, 4, 5]
After:  ['Start', 1, 2, 3, 4, 5]

Example-2

lst = [1,2,3,4,5]

print('Before: ',lst)

lst.insert(5,'Start')  #Inserting At The End Index

print('After: ',lst)
Output:
Before:  [1, 2, 3, 4, 5]
After:  [1, 2, 3, 4, 5, 'End']

(c) Using extend() Method

  • extend() method will add multiple elements at the end of the list.
  • append() method can add only a single element at the end of the list.
  • In case of append() method, if you add a whole list , it will take the list as a single element.
  • But, in case of extend() method, if you are adding a whole list, it will add all the elements inside the 2nd list to the 1st list.

Example-1

lst = [1,2,3,4,5]

print('Before: ',lst)

lst.extend([6,7,8,9,10])

print('After: ',lst)
Output:
Before:  [1, 2, 3, 4, 5]
After:  [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

Example-2

lst = [1,2,3,4,5]

print('Before: ',lst)

lst.extend(['a','b','c','d','e'])

print('After: ',lst)
Output:
Before:  [1, 2, 3, 4, 5]
After:  [1, 2, 3, 4, 5, 'a', 'b', 'c', 'd', 'e']

(d) Difference Between append() and extend() Method

  • extend() method will add multiple elements at the end of the list.
  • append() method can add only a single element at the end of the list.
  • In case of append() method, if you add a whole list , it will take the list as a single element.
  • But, in case of extend() method, if you are adding a whole list, it will add all the elements inside the 2nd list to the 1st list.

Example- append()

lst = [1,2,3,4,5]

print('Before: ',lst)

lst.append([6,7,8,9,10])

print('After: ',lst)
Output:
Before:  [1, 2, 3, 4, 5]
After:  [1, 2, 3, 4, 5, [6, 7, 8, 9, 10]]

Example- extend()

lst = [1,2,3,4,5]

print('Before: ',lst)

lst.extend([6,7,8,9,10])

print('After: ',lst)
Output:
Before:  [1, 2, 3, 4, 5]
After:  [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

Note:

  • Here you can see the difference in the output of both the examples.
  • append() : [1, 2, 3, 4, 5, [6, 7, 8, 9, 10]]
  • extend() : [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
  • In case of append() method the list is added as it is.
  • But, in case of extend() the elements inside the list is added .

(7) Removing Elements From A Python List

  • If you want to remove some elements from the list, you can also do that.
  • Python provides below inbuild methods to remove an element from the list.
    (1) remove()
    (2) pop()

(a) Using remove() Method

  • If you want to remove an element from the list you can use remove() method.
  • It will remove the first occurrence of the searched element from the list.
  • If the element doesn’t exist it will raise an error.
  • Remove() method only removes one element at a time, to remove a range of elements, you can use for loop.

Example

lst = [2,2,8,7,3,6,6,7]

print('Before: ',lst)

lst.remove(6) #Remove The Fist 6.

print('After: ',lst)

lst.remove(6) #Remove The Second 6.

print('After: ',lst)
Output:
Before:  [2, 2, 8, 7, 3, 6, 6, 7]
After:  [2, 2, 8, 7, 3, 6, 7]
After:  [2, 2, 8, 7, 3, 7]

(b) Using pop() Method

  • pop() method will removes only the last element of the list and it wil return the removed element.
  • If you want to remove element at a particular index position you can pass the index position to the pop() method.

Example-1

lst = [1,2,3,4,5]

print('Before: ',lst)

lst.pop() # Pop the last element from list.

print('After: ',lst)

lst.pop() # Pop the last element from list.

print('After: ',lst)
Output:
Before:  [1, 2, 3, 4, 5]
After:  [1, 2, 3, 4]
After:  [1, 2, 3]

Example-2

lst = [1,2,3,4,5]

print('Before: ',lst)

lst.pop(2) # Remove the element at index 2

print('After: ',lst)

lst.pop(1) # Remove the element at index 1

print('After: ',lst)
Output:
Before:  [1, 2, 3, 4, 5]
After:  [1, 2, 4, 5]
After:  [1, 4, 5]

(8) Reversing A Python List

  • You can reverse a python list by using reverse() method.
  • reverse() method will update the original list.

Example-1

lst = [1,2,3,4,5,6,7,8,9,10]

print('Before: ',lst)

lst.reverse()

print('After: ',lst)
Output:
Before:  [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
After:  [10, 9, 8, 7, 6, 5, 4, 3, 2, 1]

Example-2

lst = ['a','b','c','d','e']

print('Before: ',lst)

lst.reverse()

print('After: ',lst)
Output:
Before:  ['a', 'b', 'c', 'd', 'e']
After:  ['e', 'd', 'c', 'b', 'a']

(9) Sorting A Python List

  • You can sort a python list by using sort() method.
  • sort() method will update the original list.
  • By default it will sort in ascending order.

Python Syntax:

list.sort(key,reverse)
  • Parameters: By default, sort() doesn’t require any extra parameters. However, it has two optional parameters:
  • reverse – If True, the list is sorted in descending order.Default is False.
  • key – function that serves as a key for the sort comparison

Example-1: Normal Sort

lst = [5,7,6,3,1,8,9,4,10,2]

print('Before: ',lst)

lst.sort()

print('After: ',lst)
Output:
Before:  [5, 7, 6, 3, 1, 8, 9, 4, 10, 2]
After:  [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

Example-2: Using Reverse Attribute

lst = [5,7,6,3,1,8,9,4,10,2]

print('Before: ',lst)

lst.sort(reverse=True)

print('After: ',lst)
Output:
Before:  [5, 7, 6, 3, 1, 8, 9, 4, 10, 2]
After:  [10, 9, 8, 7, 6, 5, 4, 3, 2, 1]

Example-3: Using Key Attribute

def square(x):
    return x*x

lst = [-1,5,6,-4,2,-3,4,8]

print('Before: ',lst)

lst.sort() #Normal Sort

print('After: ',lst)

lst.sort(key=square) #Sorting Using Key

print('After: ',lst)
Output:
Before:  [-1, 5, 6, -4, 2, -3, 4, 8]
After:  [-4, -3, -1, 2, 4, 5, 6, 8]
After:  [-1, 2, -3, -4, 4, 5, 6, 8]

Note:

  • Key attribute is used to specify your own sorting technique.
  • Here I have defined my sorting technique by using a function called square().
  • So, before sorting I am squaring the numbers and after that It will sort it.
  • So after squaring the numbers the values will be [1,25,36,16,4,9,16,64]. And it will sort accordingly.

(10) Joining Python List

  • You can join different lists using bellow different techniques.
    (1) + Operator.
    (2) append() Method.
    (3) extend() Method.

Example-1

lst1 = [1,2,3,4,5]

lst2 = [5,6,7,8,9,10]

combined = lst1 + lst2

print(combined)
Output:
[1, 2, 3, 4, 5, 5, 6, 7, 8, 9, 10]

Example-2

lst1 = [1,2,3,4,5]

lst2 = ['a','b','c','d','e']

combined = lst1 + lst2

print(combined)
Output:
[1, 2, 3, 4, 5, 'a', 'b', 'c', 'd', 'e']

(11) Copying Python List

  • You cannot copy a list simply by typing list2 = list1, because: list2 will only be a reference to list1, and changes made in list1 will automatically also be made in list2.
  • You can use copy() method to copy one list.
  • You can also use inbuild list() method to copy the list.

Example-1: Problem With = Operator

lst1 = [1,2,3,4,5]

print(lst1)

lst2 = lst1 # List Copying Using = operator.

print(lst2)

lst2.append('Hello') # Changing Second List.

print(lst1)

print(lst2)
Output:
[1, 2, 3, 4, 5, 'a', 'b', 'c', 'd', 'e']

Note:

  • Here you can see that when I change ‘lst2’ the original list ‘lst1’ also got changes.

Example-2: Using Copy Method

  • To solve the issues with = operator we can use copy() method.
lst1 = [1,2,3,4,5]

lst2 = ['a','b','c','d','e']

lst2 = lst1.copy() # Copying Using Copy Method

print(lst2)

lst2.append('Hello')

print(lst1)

print(lst2)
Output:
[1, 2, 3, 4, 5]
[1, 2, 3, 4, 5]
[1, 2, 3, 4, 5, 'Hello']

Note:

  • Here you can see that there is no change on original list ‘lst1’ after making changes on ‘lst2’.

Example-3: Using list() Method

  • You can use inbuild list() method to copy the list.
lst1 = [1,2,3,4,5]

lst2 = ['a','b','c','d','e']

lst2 = list(lst1) # Copying Using list() Method

print(lst2)

lst2.append('Hello')

print(lst1)

print(lst2)
Output:
[1, 2, 3, 4, 5]
[1, 2, 3, 4, 5]
[1, 2, 3, 4, 5, 'Hello']

Note:

  • Here you can see that there is no change on original list ‘lst1’ after making changes on ‘lst2’.

(12) Slicing Python List

  • If you want to get some part of the list you can use slice technique.
  • Slice operation is performed on Lists with the use of a colon(:).

Syntax Of Slicing:

list[start index : end index : steps]
  • Start Index: Specify The Starting Index From Where You Want To Slice.
  • End Index: Specifies The End Index Till When You Want To Slice. End Index = (End Index – 1)
  • Step Size: Specifies The Number Of Steps It Need To Jump From Start To End Index.

Example-1

lst = [1,2,3,4,5,6,7,8,9,10]

print(lst[:]) #By Default It Will Start From Beginning Till End.

print(lst[2:]) #If You wont Mention End Index It Will Go Till End.

print(lst[:8]) #If You Wont Mention Start Index It Will Start From Beginning.

print(lst[2:6]) #It will Start From 2nd Index Till 6-1 = 5th Index.

print(lst[1:8:2]) # It Will Jump 2 Steps While Printing The List.

print(lst[::-1]) # It Will Print The List In Reverse Direction.

print(lst[8:1:-1]) #It Will Start From index 8 till Index 1+1 = 2

print(lst[8:2:-1]) #It Will Start From index 8 till Index 2+1 = 3
Output:
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
[3, 4, 5, 6, 7, 8, 9, 10]
[1, 2, 3, 4, 5, 6, 7, 8]
[3, 4, 5, 6]
[2, 4, 6, 8]
[10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
[9, 8, 7, 6, 5, 4, 3]
[9, 8, 7, 6, 5, 4]

(13) List Comprehension.

  • List comprehension offers a shorter syntax when you want to create a new list based on the values of an existing list.
  • By using list comprehension you can write a single line statement to create a list from an existing list.

Example-1: Before List Comprehension

fruits = ["apple", "banana", "cherry", "kiwi", "mango"]
newlist = []

for x in fruits:
    if "a" in x:
        newlist.append(x)

print(newlist)
Output:
['apple', 'banana', 'mango']

Example-2: After List Comprehension

fruits = ["apple", "banana", "cherry", "kiwi", "mango"]

newlist = [x for x in fruits if "a" in x]

print(newlist)
Output:
['apple', 'banana', 'mango']

Note:

  • Here you can see that I have used a single line statement to do the operation.
  • The first ‘x’ is the values that the new list is going to have, based on the for loop.

Leave a Reply

Your email address will not be published. Required fields are marked *