Python List
Python List

Python List

List is the most versatile Data Type in Python programming. We use a Python list to store the sequence of Python objects. In other words, we can say that List is a collection of Python objects.

Here, we have used the word ‘versatile’ because List is a flexible data type that can store any type of data. We can modify the List as many times as we require by adding and deleting list items. In comparison with other programming languages, a list is just like a dynamic array.

How to create a list in Python?

In Python, we can create a list using square brackets []. We can create a list by placing elements inside the square brackets. For example,

mylist1 = [1, 2, 3, 4]
print(type(mylist1))
print('List1:', mylist1)

mylist2 = ['a', 'bc', 'xyz']
print(type(mylist2))
print('List2:', mylist2)

Output:

<class 'list'>
List1: [1, 2, 3, 4]
<class 'list'>
List2: ['a', 'bc', 'xyz']

We can also create an empty list and add elements later. We will how to add elements in next section.

How to access items in a python list?

We can access list items using indexing and slicing.

Indexing

Elements inside a list are in an ordered sequence. In Python, whenever there is an ordered sequence, each element has an Index. Indexing starts from 0. Therefore, the index of the first element is 0, the index of the second element is 1, and so on.

Python also supports negative indexing. In negative indexing, the element is accessed from the end of the List. Therefore, the index of the last element is -1, the second last element is -2, and so on.

With the help of index, we can access any element of a list. For example,

mylist = ['apple', 'banana', 'orange', 'mango']

#accessing element with index 0
print('Element at index 0:', mylist[0])

#accessing element with index 2
print('Element at index 2:', mylist[2])

#accessing element with negative indexing
print('Element at index -1:', mylist[-1])

Output:

Element at index 0: apple
Element at index 2: orange
Element at index -1: mango

Slicing

Slicing is just like taking a slice (or part) of a full sequence. By slicing, we can access a part of the list. Instead of a single item, we can access multiple items from the list. We can use slicing with the help of slicing operator colon(:).

Syntaxlist[start : end : step]

mylist = ['a', 'b', 'c', 'd', 'e', 'f', 'g']

#slicing from start index to index before 3
print('Slicing without start index:', mylist[:3])

#slicing from index 2 to end index
print('Slicing without end index:', mylist[2:])

#slicing from index 1 to index before 5
print('Slicing with start and end index:', mylist[1:5])

#slicing from index 0 to index before 6 with 2 steps
print('Slicing with step:', mylist[0:6:2])

Output:

Slicing without start index: ['a', 'b', 'c']
Slicing without end index: ['c', 'd', 'e', 'f', 'g']
Slicing with start and end index: ['b', 'c', 'd', 'e']
Slicing with step: ['a', 'c', 'e']

How to add elements in a Python list?

To add elements in a List we have three built-in methods available in Python. We will see use of each one of them.

append()

We can use append() method to insert elements in List one at a time. It inserts the specified element at the end of the list. For example,

animals = ['tiger', 'lion', 'zebra']
print('Original list:')
print(animals)

#adding 'fox' to the list
animals.append('fox')
print('After adding new element:')
print(animals)

Output:

Original list:
['tiger', 'lion', 'zebra']
After adding new element:
['tiger', 'lion', 'zebra', 'fox']

insert()

We can use insert() method to insert element at a specified location (or index) in the List. Unlike append(), it can insert element at any position inside the list. This method takes two arguments. First is the index where the new item is to be inserted and second one is the item that needs to be inserted.

Syntax insert(index, item)

animals= ['tiger', 'lion', 'zebra']
print('Original list:')
print(animals)

#adding 'elephant' at index 2
animals.insert(2, 'elephant')
print('After inserting new element:')
print(animals)

Output:

Original list:
['tiger', 'lion', 'zebra']
After inserting new element:
['tiger', 'lion', 'elephant', 'zebra']

extend()

We can use extend() method to insert multiple items at the same time in a List. This method takes any sequence or iterable as its parameter. We can pass any sequence(list, tuple, dictionary, or string) as its parameter and the list will be extended using elements of that sequence.

Syntax – list_name.extend(iterable)

mylist = ['tiger', 'lion', 'zebra']
print('Original list:')
print(mylist)

#extending list by adding another list
mylist.extend(['deer', 'bear'])
print('List after extending:')
print(mylist)

Output:

Original list:
['tiger', 'lion', 'zebra']
List after extending:
['tiger', 'lion', 'zebra', 'deer', 'bear']

How to modify or change elements of Python list?

We can modify or change the elements of a list using Indexing and Slicing. We need to access the item that needs to be changed. After accessing that item, we can simply reassign it to the new value. For example,

lst1 = [10, 20, 35, 40]
print('Original List1:', lst1)
lst2 = [5, 15, 25, 35, 45]
print('Original List2:', lst2)

#modifying list using indexing
lst1[2] = 30
print('Modified List1:', lst1)

#modifying list using slicing
lst2[2:4] = [20, 30]
print('Modified List2:', lst2)

Output:

Original List1: [10, 20, 35, 40]
Original List2: [5, 15, 25, 35, 45]
Modified List1: [10, 20, 30, 40]
Modified List2: [5, 15, 20, 30, 45]

How to remove elements from Python list?

We have three options to delete or remove list elements.

Removing element by name

We can remove a particular element using remove() method. This method is used to remove specified element from list. We simply need to put the element name as its argument and it will remove the element. For example,

mylist = ['rose', 'daisy', 'sunflower', 'lily']
print('Original list:')
print(mylist)

#removing 'sunflower' from list
mylist.remove('sunflower')
print("New list after removing 'sunflower':")
print(mylist)

Output:

Original list:
['rose', 'daisy', 'sunflower', 'lily']
New list after removing 'sunflower':
['rose', 'daisy', 'lily']

Removing element by Index

We can also remove an element using its index. For this, we have the pop() method. We simply need to pass the index of the element that needs to be removed. If we do not specify an index it will remove the last element from the list.

Syntax – list_name.pop(index)

In addition, we can also use del keyword available in Python to delete an element. For example,

lst1 = ['ferrari', 'BMW', 'audi', 'jeep']
lst2 = ['honda', 'maruti', 'suzuki', 'tata']
lst3 = ['ktm', 'bullet', 'bugati', 'yamaha']
print('List1:', lst1)
print('List2:', lst2)
print('List3:', lst3)

#removing element at index 1 from list1
lst1.pop(1)
print('List1 after removing element at index 1:')
print(lst1)

#removing element from last index from list2
lst2.pop()
print('List2 after removing element from last index:')
print(lst2)

#removing element at index 2 using del
del lst3[2]
print('List3 after deleting element at index 3:')
print(lst3)

Output:

List1: ['ferrari', 'BMW', 'audi', 'jeep']
List2: ['honda', 'maruti', 'suzuki', 'tata']
List3: ['ktm', 'bullet', 'bugati', 'yamaha']
List1 after removing element at index 1:
['ferrari', 'audi', 'jeep']
List2 after removing element from last index:
['honda', 'maruti', 'suzuki']
List3 after deleting element at index 3:
['ktm', 'bullet', 'yamaha']

Removing all elements from list

Lastly, we have the option to empty the list. In other words, we can remove all elements of the list without deleting the list. For this we use clear() method. For example,

mylst = [1, 2, 3, 4]
print('Original list:', mylst)

#clearing full list
mylst.clear()
print('List after clear:', mylst)

Output:

Original list: [1, 2, 3, 4]
List after clear: []

Properties of a Python list

Mutability

Python lists are mutable. That means we can add, modify or delete elements from a list any number of times. We have seen several methods to add elements to the list, to remove elements from the list, and modify elements of the list. This is the most significant property of the lists that make them flexible and versatile data structure.

Ordered Sequence

Elements inside a list are ordered. That means the sequence in which elements are present in a list remains the same and all the elements have fixed index.

Data types of list items

A list can consist of different objects where datatype of each object may be different. For example,

mylist = [1, 'xyz', True, 12.32]
print(type(mylist[0]))
print(mylist[0])
print(type(mylist[1]))
print(mylist[1])
print(type(mylist[2]))
print(mylist[2])
print(type(mylist[3]))
print(mylist[3])

Output:

<class 'int'>
1
<class 'str'>
xyz
<class 'bool'>
True
<class 'float'>
12.32

Length of the list

The length of the list determines the total number of elements present inside the list. Python lists can store any number of elements. In addition, length of list need not be fixed and it can be changed anytime based on the requirement. Also, we can determine the length of a list using len() method. For example,

mylist = ['xyz', False, 12, 34, 0.32]
print('Length of list:', len(mylist))

Output:

Length of list: 5

What operations can be performed on Python list?

A. Concatenation

The concatenation (+) operator concatenates the two lists into a single list. Two lists that need to be concatenated are connected by the (+) operator.

l1 = [1, 2, 3]
l2 = [4, 5, 6]

#conatenating two lists
l = l1 + l2
print('Concatenated list:', l)

Output:

Concatenated list: [1, 2, 3, 4, 5, 6]

B. Repetition

Repetition means repeating the same sequence multiple times. It enables the list elements to be repeated multiple times. Repetition can be done by (*) operator. It’s similar to multiplication.

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

#repeating list 3 times using repetition
newlst = lst * 3
print('Repeated list:', newlst)

Output:

Repeated list: ['a', 'b', 'c', 'a', 'b', 'c', 'a', 'b', 'c']

C. Iteration

Iteration means to iterate through all the elements of a sequence. For iteration we can loop over all the elements of the list. We generally use for loop to iterate over all the elements of a list. For example,

colors = ['red', 'yellow', 'green', 'blue']

#iterating through all colors of the list
for color in colors:
    print(color)

Output:

red
yellow
green
blue

D. Membership

Membership operation determines whether an element is the member of a list. It can be determined by using membership (in) operator. For example,

veggies = ['potato', 'tomato', 'brinjal', 'chilli']

#checking for 'brinjal' in the list
print("Is 'brinjal' present in veggies:")
print('brinjal' in veggies)

#checking for 'ginger' in the list
print("Is 'ginger' present in veggies:")
print('ginger' in veggies)

Output:

Is 'brinjal' present in veggies:
True
Is 'ginger' present in veggies:
False

Python List methods

Python has various built-in methods for List. Following is the list of such methods.

MethodDescription
append()As we have already seen this method is used to add an element at the end of the list
clear()As we have already seen this method deletes all the elements of a list
copy()This method is used to create a copy of the list
count()This method is used to count the occurrence of a specified element in the list
extend()As we have already seen this method is used to add elements of any list or any other sequence at the end of specified list
index()This method returns the index of first occurrence of specified element in the list
insert()As we have already seen this method is used to insert an element at specific index in the list
pop()As we have already seen this method removes the element from the list
remove()As we have already seen this method removes the specified element from the list
reverse()This method reverse order of elements inside a list
sort()This method sorts the list in ascending order

Conclusion

In this article, we have read about creating Python lists, indexing, slicing, adding, deleting, and modifying elements of the list. We have also read about important properties of the Python lists, operations that we can perform on the lists, and built-in methods of the list. You can about python tuples, which are an immutable version of lists in this article on python tuple. You may also read this article on python string to learn about python strings.

Piyush Sharma

Third-year computer engineering student inclined towards the latest trends and technology. Always keen to explore and ready to learn new things. To read more articles on Python, stay tuned to avidpython.com.

Leave a Reply