How to create add update delete List Python

In this article, we will learn how to create add update delete List Python for beginners. Also, we will learn how to create a Python list and different types of lists, how to access list elements, How to add elements to the List, How to delete elements from the list, How to update the list, and How to Slicing of lIst.

What is Python List


The list is a sequential and ordered collection data type in Python that is represented by square brackets([]) and each item in the list is separated by a comma(,). The List can store elements of any data type like (string, boolean, int) that are changeable(item can be removed, added, updated once created), or duplicated. It is similar to a dynamic array in other languages (ArrayList in C#, Java). We can store data of different types of objects in a single list.

1. How to Create a List empty list in Python


  • Lists in python are created by placing the elements in square brackets[] separated by a comma.
  • Using the List constructor list() , which is used to create a list.

1.1 Create single list in Python using [] brackets


In this below example we have created an empty list using [] bracket, a list of strings, and a list of mixed datatypes As we can see a list can have different types of elements(int, float, string) as well as duplicate items.

print('Different ways to create a List :')

#an empty list 

alph_List = []
print(alph_List)

#list of string

pre_List = ['at','on','into','up','up']
print(pre_List)

#list of mixed data types 

mixed_type_list = [12,24,2.5,2.5,'upto']
print(mixed_type_list )

#list of number

num_list = [10,20,30,40,10]

print(num_list)


Output

Different ways to create a List :

[]

['at', 'on', 'into', 'up', 'up']

[12, 24, 2.5, 2.5, 'upto']

[10, 20, 30, 40, 10]

1.2. Create a Nested List or list of lists using [] brackets


A list inside another list is called a nested list also known as a Multidimensional list or a list of lists. Just like a single list, a nested list can have elements of different data types as well as duplicate elements.

Python Program to create nested list Using brackets

#nested list of mixed data-types

pre_List = [['at','on','into'],[12,24,2.5,2.5]]

print('Nested List:')

print(pre_List)

Output

Nested List:

[['at', 'on', 'into'], [12, 24, 2.5, 2.5]]

1.3. Create a list using a List constructor


To create a list using the list constructor we pass the elements in the list() constructor.

Syntax

#create list using list constructor


listname = list((element1-----elementn))
#create a list using list constructor

pre_list = list(("at", "up",20,30,2.5,4.5)) 

print(pre_list)

#create nested list using list constructor

nested_list = list((["at", "up",20,30,2.5,4.5],[12,34,16])) 

print(nested_list )

Output

['at', 'up', 20, 30, 2.5, 4.5]

[['at', 'up', 20, 30, 2.5, 4.5], [12, 34, 16]]

2. How to Access List elements in Python


There are three ways to access elements of the list.

  • List Posting Indexing
  • Negative Indexing
  • Range of index

2.1 Access Python List element using Positive Index


List element is accessed by an index by providing the index of the element in square brackets([]). The index of the list elements starts from 0 and so on. A list of n elements will have an index range of start index is 0 and the last index is n-1.

Syntax

listname[index]

Important Note:

  • The index must be an integer type, it can not be a float.
  • To avoid IndexError (out of range) pass index in range, A list has 7 elements, has index range will be 0 to 6, accessing index except these indexes will throw IndexError: out of range exception.

Python Program to Access list element by positive index

pre_List = ['at','on','into','up','The']

print('Accessing single list:')
print(pre_List[1])
print(pre_List[3])
print(pre_List[4])



print('\n Accessing nested list:')
nested_list = list((["at", "up",20,30,2.5,4.5],[12,34,16])) 
print(nested_list[0][1])
print(nested_list[0][2])
print(nested_list[0][3])
print(nested_list[1][1])

#passing an index of float type

print(pre_List[1.3])

Output

Accessing elements of a single list by Index:
on
up
The

Accessing elements of a nested list by Index:
up
20
30
34

Traceback (most recent call last):
  File "main.py", line 27, in <module>
    print(pre_List[1.3])
TypeError: list indices must be integers or slices, not float

2.2 Access python List elements Using Negative Indexing


The list element is accessed by providing the Negative index in the square bracket([]) the negative index starts from the end. So -1 is for the first last element, -2 for the second last element, and so on till the list length.

Python Program to Access list elements by Negative Index

#Accessing single list element by negative Index

pre_List = ['at','on','into','up','The']


print('Accessing single list element by negative Index:')
print(pre_List[-1])
print(pre_List[-2])
print(pre_List[-3])
print(pre_List[-4])
print(pre_List[-5])


#Accessing nested list by negative Index

print('\nAccessing nested list by negative Index:')

nested_list = list(([ "up",30,2.5,4.5],[12,34,"at"])) 
print(nested_list[0][-1])
print(nested_list[0][-2])
print(nested_list[0][-3])
print(nested_list[0][-4])

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

Output

Accessing single list element by negative Index:
The
up
into
on
at

Accessing nested list by negative Index:
4.5
2.5
30
up
at
34
12

2.3 Access Python List element Using Range of Indexes


We access the range of elements by index we pass the start and end index in a square bracket([]). It returns a new list of elements those fall in the index range.

Python Program to Access mutiple elements by Range of Indexes

pre_List = ['at','on','into','up','The']


print('Accessing  list element range of indexes:\n')

print(pre_List[1:4])

print(pre_List[0:3])

print(pre_List[0:5])

Output

Accessing  list element range of indexes:

['on', 'into', 'up']

['at', 'on', 'into']

['at', 'on', 'into', 'up', 'The']

Accessing list elements by Range of negative Indexes

pre_List = ['at','on','into','up','The']


print('Accessing  list element range of negative indexes:\n')

print(pre_List[-4:-1])

print(pre_List[-3:-2])

print(pre_List[-3:-1])

Output

Accessing  list element range of negative indexes:

['on', 'into', 'up']

['into']

['into', 'up']

3. How to slice a list in Python


: slicing operator is used to do slicing in Python. It returns the new list of elements that pass the given slicing range from the existing list.

Python Program to slice list elements

pre_List = ['at','on','into','up','The']
 
#start from index 1 to end at 3, element at index 3 (will not be included)

print(pre_List[1:3])


#start from index 0 to end at 3, element at index 3 (will not be included)

print(pre_List[:3])


#element at index 3 till end of list 

print(pre_List[3:])


#print the whole list start to end 

print(pre_List[:])


# from 2 last element  to start(index 0)

print(pre_List[:-2])


Output

['on', 'into']

['at', 'on', 'into']

['up', 'The']

['at', 'on', 'into', 'up', 'The']

['at', 'on', 'into']

4. How to get Length of a List in Python


The Len() method is used to get the length of the list in Python

pre_List = ['at','on','into','up','The']

#len() method to get length of list

List_len = len(pre_List)
 
print('list Length :',List_len)

Output

list Length : 5

5. How to add elements in Python List


  • append()
  • Extend()
  • Insert()

4.1 Add/append an element to Python List using Append()


The append() method of the list is to append an element, iterable( list, tuple, string, dictionary, set) append in the list. The size of the list change after appending the element to the list.

Note: The iterable will append as an object at end of the list not one by one element of iterable.

Python Program to add elements to Python List

orginal_list = ['at','on','into']
num_list = [12,13]
my_dict = {'A':65,'B':66}
my_set = {1,2}
my_str = 'upon'


print('before append element:\n',orginal_list)

#appending an element
orginal_list.append('data')


#appending an list
orginal_list.append(num_list)
 
#appending a dict 
orginal_list.append(my_dict)


#appending  a set
orginal_list.append(my_set)


#appending a string
orginal_list.append(my_str)

print('original list with appended element:\n',orginal_list)

Output

before append element:
 ['at', 'on', 'into']

original list with an appended element:

 ['at', 'on', 'into', 'data', [12, 13], {'A': 65, 'B': 66}, {1, 2}, 'upon']

4.2 Add mutiple elements to Python list using Extend()


Extend() method adds iterable(list, tuple, string, dictionary, set) at the end of the list, unlike append it iterates over elements of iterable and adds one by one to the end of the list.

Note: the size of the list increase by the number of elements in each iterable.

#extend() iterable to list 

orginal_list = ['at','on']
num_list = [12,13]
my_dict = {'A':65,'B':66}
my_set = {1,2}
my_str = 'upon'


print('before extend iterable:\n',orginal_list)

#appending an element
orginal_list.extend('data')

#extending an list
orginal_list.extend(num_list)
 
#extending a dict 
orginal_list.extend(my_dict)

#extending a set
orginal_list.extend(my_set)

#extending a string

orginal_list.extend(my_str)

print('original list after extended iterables:\n',orginal_list)

print('list length :',len(orginal_list))

Output

list before extend iterable:
 ['at', 'on']

original list after extended iterables:
 ['at', 'on', 'd', 'a', 't', 'a', 12, 13, 'A', 'B', 1, 2, 'u', 'p', 'o', 'n']

list length : 16

4.3Add element at a specific index in Python List


Insert() method add multiple elements at a specific index in the list. The first argument is an index and the second is an element we want to insert.

original_list = ['at','on','up']


#inserting at index 0
original_list.insert(0,14)

#inserting at index 1
original_list.insert(1,12)

#inserting at index 2
original_list.insert(2,'onto')


print(original_list)


Output

[14, 12, 'onto', 'at', 'on', 'up']

5. How to update a list in Python


A list in Python is updated using the = operator or slicing. Let us understand with an example how to achieve this.

Python Program to update a list in Python

original_list = ['at','on','up']


#updating list elemnst at 0 index
original_list[0] = 'above'

#update element using slicing
original_list[3:5] = ['in','into']


print(original_list)

Output

['above', 'on', 'up', 'in', 'into']

6. How to delete elements from a List in Python


These are methods to delete or remove elements from the list.

  • Del: The del statement is used to delete item by index,single, multiple elements, or a whole list.
  • Pop() : It removes elements at specific Index.
  • remove() : It is used to remove the passed element as a parameter.
  • clear() : It clear() the list.

Python Program to Delete elements from List using Del

original_list = ['at','on','up','in','upon']

# delete single element
del original_list[1]

print('after deletion:',original_list)

# delete multiple items
del original_list[1:4]

print('after deletion :',original_list)

# delete the full list

del original_list

Output

after deletion: ['at', 'up', 'in', 'upon']

after deletion: ['at']

Python Program to Delete elements Using Pop(),remove(),clear()

original_list = ['at','on','up','in','upon']

# delete a single element at index 1

original_list.pop(1)

print('after pop() :',original_list)

# removing the 'upon' from the list

original_list.remove('upon')

print('after remove() :',original_list)

# clear the full list

original_list.clear()

print('after clear() :',original_list)

Output

after pop() : ['at', 'up', 'in', 'upon']

after remove() : ['at', 'up', 'in']

after clear() : []

Conclusion:

In this post we understood How to create add update delete List Python that also includes what is a list, and how to create, add, delete, and update elements from a List with code examples.