Python List create add update delete

Python List

In this article, we are going to understand the Python List create add update delete 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 in List, How to delete elements from the list, How to update the list, Slicing of lIst

What is Python List


The list is an in-built ordered collection of sequence 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), 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 Python List


  • 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.

Example

mylist  = ['A','B','C','D']

1.1 Create single list in Python using [] brackets


This is a code example of different ways to create a single, As we can see a list can have different types of elements(int, float, string) as well as duplicate items.

Python Program to create list Using brackets

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 using [] brackets


List inside another list is called nested list also know as Multidimensional list. 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 list using 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))

Example create single list using list constructor

#create a list using list constructor

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

print(pre_list)

Output

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

4. Create Nested List using List constructor

#create nested list using list constructor

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

print(pre_list)

Output

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

2. How to Access List elements


There are three ways to access elements of the list.

  • List Postive Indexing
  • Negative Indexing
  • Range of index

Access Python List element using Postive 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

Access python List elements Using Negative Indexing


The list element is accessed by providing the Negative index in 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

Access Python List element Using Range of Indexes


We access the range of elements by index we pass the start and end index in 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 do Python List slicing


: slicing operator is used to doing 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']

How to get Length of Python List


Len() method is used to get the length of 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

4. How to add elements in Python List


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

4.1 Add/append 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 add 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 end of the list.

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

Python Program to Add multiple elements to Python list

#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 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.

Python Program to add element at specific index in Python List

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 = 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 List


These are methods to delete or remove elements from list.

  • Del: It can be used to delete 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 List in Python with Code Example like what is a list, how to create, add, delete, update elements from List with code examples.