List in Python

  • Lists are just like the arrays, declared in other languages.
  • It needs not to be homogeneous always which makes it the most powerful tool in python.
  • A single list may contain datatype like integers, strings as well as to object.
  • These are mutable and hence they can be altered even after their creation.
  • List in Python are ordered and have a definite count.
  • These are used to store multiple items in a single variable.
  • It is one of the most frequently used and very versatile data types used in Python.
  • A data structure is a collection of data elements such as numbers or characters or even other data structures.
  • The most basic data structure in Python is the sequence.

Please read the previous topic for more understanding about Control Statements
Python String Formatting
Boolean in Python
Python Operators

Control Statements in Python

Initialize / Creating a List in Python 

  • In Python programming, a list is created by placing all the items (elements) inside square brackets [], separated by commas.
  • It can have any number of items and they may be of different types (integer, float, string etc.).
  • These are enclosed by [].
  • Each item in the list has an assigned index value and is separated by a comma.
# empty list
list1 = []  #Intial blank list
print(list1)


# list of integers
list2 = [1,2,3,4,5]
print(list2)

# list with mixed data types
list3 = [1, 4.5, "Paris"]
print(list3)


# list of list
list4 = [[1,2,3],['Tokyo', 'London', 'Dubai']]
print(list4)

Output-

[]
[1, 2, 3, 4, 5]
[1, 4.5, 'Paris']
[[1, 2, 3], ['Tokyo', 'London', 'Dubai']]

Access Elements List in Python

To access list items individually, you can use an index just like an array. You can also access a range of items in the list by giving range as the index. The index must be an integer or integer expression.

List in Python
List in Python with indexes

Index base Access

Indexing in a List are of two types:
Positive Indexing – Here the indexing starts from 0, moving from left to right.
Negative Indexing – In this, the indexing starts from right to left and the rightmost element has an index value of -1.

myList = [ 98, 42, 78, 43, 12, 87 ]
print(myList[0])
print(myList[5])
print(myList[-1])
print(myList[-6])

# 8 index is not available in list so we get the error 
print(myList[8])

Output-

List in Python

Python List Slicing

List in Python, slicing is a common practice and it is the most used technique for programmers to solve efficient problems. Consider a python list, In-order to access a range of elements in a list, you need to slice a list. One way to do this is to use the simple slicing operator i.e. colon(:)

With this operator, one can specify where to start the slicing, where to end and specify the step. List slicing returns a new list from the existing list.

Syntax:

List[ Initial : End : IndexJump ]

If Lst is a list, then the above expression returns the portion of the list from index Initial to index End, at a step size IndexJump.

myList = [ 98, 42, 78, 43, 12, 87 ]

#Positive index Slicing
print(myList[2:5])
print(myList[2:])
print(myList[:4])


print(myList[1:5:2])

Output-

[78, 43, 12]
[78, 43, 12, 87]
[98, 42, 78, 43]
[42, 43]
myList = [ 98, 42, 78, 43, 12, 87 ]
#Negative index Slicing
print(myList[-5:-2])
print(myList[-2:])
print(myList[:-4])

print(myList[-6:-1:2])

Output-

[42, 78, 43]
[12, 87]
[98, 42]
[98, 78, 12]

Multi-dimensional lists in Python

Lists in Python can have more than one additional dimension. Keeping in mind that a list can hold other lists, that basic principle can be applied further. Multidimensional lists are lists within lists. Usually, a dictionary would be a better choice instead of a multidimensional list in Python.

myList = [[2, 4, 6], [3, 5, 7], [10,20,30]]

print(myList)
print(myList[2])
print(myList[2][1])
print(myList[-3])
print(myList[-3][-2])

Output-

[[2, 4, 6], [3, 5, 7], [10, 20, 30]]
[10, 20, 30]
20
[2, 4, 6]
4

Useful Function in Python List

Adding Elements to a List in Python

Only one element at a time can be added to the list by using append(). For the addition of multiple elements with the append() method, loops are used. Tuple, Set, List can also be added to the list with the use of the append method.

lst = [2,4,6,8,10]
print(lst)
lst.append(12)
print(lst)

Output-

[2, 4, 6, 8, 10]
[2, 4, 6, 8, 10, 12]

Append a list with another list in Python

List1 = [2,4,6,8,10]
List2 = ["Hello", "World"]

#Before Append
print(List1)
print(List2)

#Append the list
List1.append(List2)

#After Append
print(List1)
print(List2)

Output-

[2, 4, 6, 8, 10]
['Hello', 'World']
[2, 4, 6, 8, 10, ['Hello', 'World']]
['Hello', 'World']

Insert Element in List

Append() method only works for the addition of element at the end of the list, for the addition of element at the desired position, the insert method is used. Unlike append() which takes only one argument, the insert() method requires two-argument (position, value)

List1 = [2,4,6,8,10]


#Before Insert
print(List1)
List1.insert(3,14)
List1.insert(0, "Hello")


#After insert item in List
print(List1)

Output-

[2, 4, 6, 8, 10]
['Hello', 2, 4, 6, 14, 8, 10]

Removing Elements from the List

Remove()

It is used to remove the element from the list but an error raises if the element does not exist in the list. Remove() method only removes one element at a time, to remove a range of elements.

Note:-
The remove method in the list will only remove the first occurrence of the search element.

List1 = [10,20,30, 40, 50, 60, 30]

#Before Remove element
print(List1)

List1.remove(10)

#After Remove element
print(List1)

#The remove method in the list will only remove the first occurrence of the search element.
List1.remove(20)

print(List1)

Output-

[10, 20, 30, 40, 50, 60, 30]
[20, 30, 40, 50, 60, 30]
[30, 40, 50, 60, 30]
List1 = [10,20,30, 40, 50, 60, 30]

#Error raises if the element does not exist in the list
List1.remove(36)

Output-

List in Python

Pop()

It is also be used to remove and return an element from the list but by default it removes only the last element of the list, to remove an element from a specific position of the list, the index of the elements is passed as an argument to the pop() method.

  • The pop() method takes a single argument (index).
  • The argument passed to the method is optional. If not passed, the default index -1 is passed as an argument (index of the last item).
  • If the index passed to the method is not in range, it throws IndexError: pop index out of range exception.
List1 = [10,20,30, 40, 50]

#Passing index to remove item in list
print(List1.pop(2))
print(List1)

#Without argument to remove item in list, It will remove last item in List
print(List1.pop())
print(List1)

Output-

30
[10, 20, 40, 50]
50
[10, 20, 40]

Clear()

  • The clear() method doesn’t take any parameters.
  • The clear() method only empties the given list. It doesn’t return any value.
  • Remove all items in list.
List1 = [10,20,30, 40, 50]

#Before Clear the List in Python
print(List1)

# clearing the list
List1.clear()


#After Clear the list in python
print(List1)

Output-

[10, 20, 30, 40, 50]
[]

Index()


index() is an inbuilt function in Python, which searches for a given element from the beginning of the list and returns the lowest index where the element appears.

Syntax:
list_name.index(element, start, end)
Parameters:
element – The element whose lowest index will be returned.
start (Optional) – The position from where the search begins.
end (Optional) – The position from where the search ends.
Returns:
Returns the lowest index where the element appears.
Error:
If any element which is not present is searched, it returns a ValueError.

List1 = [10,20,30, 40, 50, 60, 70, 80]

print(List1.index(30))

print(List1.index(80, 1))

print(List1.index(60, 1, 7))

Output –

2
7
5
List1 = [10,20,30, 40, 50, 30, 60, 70, 30]

#It will return only first element index
print(List1.index(30))

Output-

2
List1 = [10,20,30, 40, 50, 30, 60, 70, 30]

#It will return only first element index
print(List1.index(14))
List in Python

Count()

Return the count of a number of items. If search item is not available in the list then it will return zero.

List1 = [10,20,30, 40, 50, 30, 60, 70, 30]

#Counting the match item in List
print(List1.count(10))
print(List1.count(30))

#If item is not available in List then it will return Zero
print(List1.count(100))

Output-

1
3
0

Sort()

The sort() method sorts the elements of a given list in a specific ascending or descending order.
By default, sort() does not require any additional parameters. However, it has two optional parameters:
reverse – if true, the sorted list is reversed (or sorted in descending order)
key – function that acts as a key for sort comparison

The sort() method doesn’t return any value. Rather, it changes the original list. If you want the function to return the sorted list instead of replacing the original list, use sorted().

List1 = [23, 6, 34, 95, 43, 94]

List1.sort()

#Sorted List in Python
print(List1)

Output-

[6, 23, 34, 43, 94, 95]

Syntax:
list.sort(key=…, reverse=…)
Alternatively, we can also use Python’s built-in sorted() function for the same purpose.
sorted(list, key=…, reverse=…)

sort() changes the list directly and doesn’t return any value, while sorted() doesn’t change the list and returns the sorted list.

List1 = ['Tokyo', 'London', 'Dubai', 'Jakarta', 'Delhi', 'Shanghai']

List1.sort()

#Sorted List in Python
print(List1)

Output-

['Delhi', 'Dubai', 'Jakarta', 'London', 'Shanghai', 'Tokyo']

Sort in descending order

The sort() method accepts a reverse parameter as an optional argument.
Setting reverse = True sorts the list in descending order.

list.sort(reverse=True)
Alternatively, for sorted(), you can use the following code.
sorted(list, reverse=True)

List1 = [23, 6, 34, 95, 43, 94]

List1.sort(reverse=True)

#Sorted List in Python
print(List1)

Output-

[95, 94, 43, 34, 23, 6]
List1 = [23, 6, 34, 95, 43, 94]
#Sort List in Python using sorted method
print(sorted(List1))
print(sorted(List1, reverse=True))

Output-

[6, 23, 34, 43, 94, 95]
[95, 94, 43, 34, 23, 6]

Reverse()

The reverse() method reverses the elements of the list.

reverse() parameter
The reverse() method doesn’t take any arguments.

Return Value from reverse()
The reverse() method doesn’t return any value. It updates the existing list.

List1 = ['Tokyo', 'London', 'Dubai', 'Jakarta', 'Delhi', 'Shanghai']

List1.reverse()

#Reverse List item in Python
print(List1)

Output-

['Shanghai', 'Delhi', 'Jakarta', 'Dubai', 'London', 'Tokyo']

copy()

The copy() method returns a shallow copy of the list.

Syntax:
new_list = list.copy()

Parameters:
The copy() method doesn’t take any parameters.

Return Value:
The copy() method returns a new list. It doesn’t modify the original list.

myList = [10,20,30, 40, 50]

#Copy the list in Python
newList = myList.copy();

print(newList)

Output-

[10, 20, 30, 40, 50]

Len()

It finds the length of the list in python.

list5 = [2,4,6,8,10]
#Length of List
print(len(list5))

Output-

5

Please download the example of List in Python

Leave a Comment

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