In this tutorial you will learn about appending the python list, python list count function, how to remove duplicates in python, remove elements from the list.

Introduction to Python list

Lists in Python are non primitive data structures. Lists are ordered, mutable or changeable and could store multiple items in a single variable. It is written within a square bracket where each element is separated with a comma. Values in lists are accessed by its index.

Forward and Backward Indexing in python list
name = ['John', 1, 2]
print(name)
[‘John’, 1, 2]
name [0] = 'R'
name
[‘R’, 1, 2]
letter = 'abcdefgABCDEFG'
list_letters = list(letter)
list_letters
[‘a’, ‘b’, ‘c’, ‘d’, ‘e’, ‘f’, ‘g’, ‘A’, ‘B’, ‘C’, ‘D’, ‘E’, ‘F’, ‘G’]

Python List Comprehension

Python provides a concise way to create  new lists from the existing list. Rather than using normal functions and loops for creating a list we can use list comprehension as it is more compact and faster than normal loops. 

We should avoid writing long List Comprehension in a single line to ensure that python code is user friendly.

veg = ["tomato", "potato", "onion", "brinjal", "garlic"] 
newlist = [x for x in veg if "a" in x]
print(newlist)
[‘tomato’, ‘potato’, ‘brinjal’, ‘garlic’]

Built-in Functions in Python List

1. Append – Add items at end

The append() method in python programming adds a single item to the existing list. It doesn’t return a new list of items but will modify the original list by adding the item to the end of the list. After executing the method append on the list the size of the list increases by one.

Employee_name = ['John', 'Doe', 'Sebastian', 'Doe']
Employee_name.append('Jack')
print(Employee_name)
[‘John’, ‘Doe’, ‘Sebastian’, ‘Doe’, ‘Jack’]

2. Copy – Return a copy of List

Sometimes, there is a need to reuse any object, hence copy methods are always of great utility. Python in its language offers a number of ways to achieve this. This particular article aims at demonstrating the copy method present in List. Since list is widely used hence, its copy is also necessary. 

Employee_name_copy = Employee_name
print(Employee_name_copy)
[‘John’, ‘Doe’, ‘Sebastian’, ‘Doe’, ‘Jack’]

3. Count – Return number of occurrences of an element

The count() method returns the number of occurrences of an element in a list. In simple terms, count() method counts how many times an element has occurred in a list and returns it.

Employee_name = ['John', 'Doe', 'Sebastian', 'Doe']
print(Employee_name.count('Doe'))

2

4. Sort – sorts element of the list

The python sort list method sorts the list in ascending order by default.

Syntax:

Python programming - sort method in python lists

Parameter Values:

passing parameters to sort method in a python list

5. Length – Return number of elements.

The len() method returns the number of elements in a python object. This python list length method is not specifically for lists but this method can be used with other python data structures.

a = "TechLearn"
len(a)

9

a = [1, 2, 3, 4]
len(a)

4

6. Reverse – Reverses the elements of the list

The reverse method() reverses the element of the list. It doesn’t take any arguments. The python reverse list method doesn’t return any value. It only updates the existing list.

Employee_name = ['John', 'Doe', 'Sebastian', 'Jack']
Employee_name.reverse()
print(Employee_name)
[‘Jack’, ‘Sebastian’, ‘Doe’, ‘John’]

7. Pop – Removes element from specified position

pop() is an inbuilt function in Python that removes and returns last value from the list or the given index value. 

Parameter : 

index (optional) – The value at index is popped out and removed.       If the index is not given, then the last element is popped out and removed.

Employee_name.pop(-1)
print(Employee_name)
[‘Jack’, ‘Sebastian’, ‘Doe’]
Employee_name.pop()
print(Employee_name)
[‘Jack’, ‘Sebastian’]

8. Remove –  Removes first occurrence of an element

The remove() method removes the first matching element (which is passed as an argument) from the list.

Parameter: 

Element- takes a single element as an argument and removes it from the list.

If the element doesn’t exist, it throws ValueError: list.remove(x): x not in list exception.

Employee_name = ['John', 'Doe', 'Sebastian', 'Doe']
Employee_name.remove('Doe')
print(Employee_name)
[‘John’, ‘Sebastian’, ‘Doe’]

9. Clear – Remove all the items from the list

The clear method() doesn’t take any parameters. The clear method() only empties the given list. It doesn’t return any value.

Employee_name.clear()
Employee_name
[]

10. Delete – Remove items by index or slice

An item which has to be deleted should be specified by its index. The first index is 0, and the last index is -1.

Employee_name = ['Jack', 'Joe', 'Sebastian', 'Doe']
del(Employee_name[2])
print(Employee_name)
[‘Jack’, ‘Joe’, ‘Doe’]

11. Index –  Returns index of element passed

The index() is used to find the index of the given element in the list.  A ValueError exception is raised, when the element is not found.

vowels = ['a', 'e', 'i', 'o', 'u']
index = vowels.index('e')
print('Index of e:', index)

index of e: 1

Accessing values from the List

To Access the data items we use indexing :

It starts from 0 to n-1 where n is the no. of items in the list.The syntax we’ll use will be list_name[index].

Employee_name = ['Akash', 'Prakhar', 'Nitish', 'Ayushi', 'Prachi', 'Srijan']
Employee_name[1]

‘Prakhar’

Average of a list in Python

By using the sum() and len() functions we can find the average of the list in python.

sum() :  we can get the sum of the list using sum() function.

len(): we can get the length or number of elements in a list by using a len() l function.

Average = sum()/len()

lst = [1, 2, 3, 4, 5]
avg = sum(lst)/len(lst)
print(avg)

3.0

List Slicing in Python

Slicing is a flexible tool to build new lists out of an existing list.

Python supports slice notation for any sequential data type like lists, strings, tuples, bytes, byte arrays, and ranges. Also, any new data structure can add its support as well. This is greatly used in NumPy and Pandas libraries, which are so popular in Machine Learning and Data Science. 

Slicing parameters: list[ start: stop: step ]

Employee_name = ['Akash', 'Prakhar', 'Nitish', 'Ayushi', 'Prachi', 'Srijan']
Employee_name[3:]
[‘Ayushi’, ‘Prachi’, ‘Srijan’]
Employee_name[1:5]
[‘Prakhar’, ‘Nitish’, ‘Ayushi’, ‘Prachi’]
Employee_name[1:5:2]
[‘Prakhar’, ‘Ayushi’]
Employee_name[::2]
[‘Akash’, ‘Nitish’, ‘Prachi’]
Employee_name[::-1]
[‘Srijan’, ‘Prachi’, ‘Ayushi’, ‘Nitish’, ‘Prakhar’, ‘Akash’]

How are Python Dictionaries different from Python Lists?

Lists in Python are the ordered collections of elements and duplicate members possible  whereas Dictionaries are unordered collections of items with no duplicate members. Values in lists are accessed by its index value whereas Values in dictionaries are accessed via keys.

How are Python Tuples different from Python Lists?

Lists in Python are mutable whereas Tuples are immutable.

Large memory blocks are allocated for tuples as compared to lists which make tuples faster than lists when there are a large number of elements.

How to find the count of duplicates in a list?

Mylist = ["t", "e", "c", "h", "l", "e", "a", "r", "n"]
count = 0
for i in Mylist:
 if i == "e":
  count = count+1
print("the no. of e in Mylist is:", count)

the no. of e in Mylist is: 2

Alternate method:

Mylist = ["t", "e", "c", "h", "l", "e", "a", "r", "n"]
print(Mylist.count('e'))

2

How to remove duplicates from a list using sets in python?

With the help of the built-in function set() we can remove the duplicates from the list. We are using the set() method because it returns distinct elements.

mylist = [1,1,2,3,2,2,4,5,6,2,1]
final_list = set(my_list)
print(list()final_list)
[1, 2, 3, 4, 5, 6]

How to remove duplicates from a list using dict in python?

By importing OrderedDict from collections we can remove duplicates from the given list.OrderedDict returns you the distinct elements in an order in which the key is present.

To get the unique values from the list we make use of list and use   fromkeys() method available in OrderedDict.

from collections import OrderedDict
mylist = ['a', 'b', 'a', 'c', 'd', 'b', 'a', 'c']
final_list = OrderedDict.fromkeys(mylist)
print(list(final_list))
[‘a’, ‘b’, ‘c’, ‘d’]

How to remove duplicates from a list using Numpy Unique() method?

To remove duplicates from the list the method unique() from Numpy module is used.

To work with  numpy we first need to import numpy modules.

import numpy as np
my_list = [1,2,2,3,1,4,5,1,2,6]
FinalList = np.unique(my_list).tolist()
print(FinalList)
[1, 2, 3, 4, 5, 6]

How to remove duplicates from a list using for loop in python?

To remove duplicates from the list we will traverse the items of the list by using for-loop.

First initialize the array to empty.Inside the for-loop, add check if the items in the list exist in the array .If the items do not exist, add the item to the array using the append() method.

So whenever the duplicate item is encountered it will be already present in the array and will not be inserted. 

my_list = [1,2,2,3,1,1,2,4,5,1,2,6]
FinalList = []
for i in my_list:
 if i not in Finallist:
  Finallist.append(i)
print(list(finallist))
[1, 2, 3, 4, 5, 6]

How to remove duplicates from a list using list comprehension?

List comprehensions are used for creating new lists from the existing list. This helps us to reduce the number of loops and make the code more easier to read and maintain.

my_list = [1,2,2,3,3,3,3,1,4,5,1,2,6]
finallist = []
[finallist.append(n) for n in my_list if n not in finallist]
print(finallist)
[1, 2, 3, 4, 5, 6]

How to remove duplicates from a list using Pandas methods

The unique method() from pandas helps us to get the unique element from the given list. For using pandas functions we first need to import the pandas module.

import pandas as pd
my_list = [1,2,2,3,1,4,4,5,6,7,5,1,2,6]
myFinalList = pd.unique(my_list).tolist()
print(myFinalList)
[1, 2, 3, 4, 5, 6, 7]

How to use for-loop to get the index of an element in a list ?

To access the index of each element in a for-loop is to go through the length of the list by increasing the index.

my_list = [3, 5, 4, 6, 7, 2, 2, 5, 5]

print("Indices and values in my_list:")

for index in range(len(my_list)):
  print(index, my_list[index], end = "\n")

Indices and values in my_list:

0 3

1 5

2 4

3 6

4 7

5 2

6 2

7 5

8 5

we don’t iterate through the list, we iterate from 0…len(my_list) with the index.

How to use list comprehension to get the index of an element in a list ?

We can use list comprehension to iterate through a list and access its indices and corresponding values. 

my_list = [1, 6, 3, 5, 4, 2, 2, 5, 5]
print("Indices and values in my_list:")
print([list((i in my_list[i])) for i in range(len(my_list))])

Indices and values in my_list:

[[0, 1], [1, 6], [2, 3], [3, 5], [4, 4], [5, 2], [6, 2], [7, 5], [8, 5]]

How to use enumerate to get the index of an element in a list ?

When we want to access both the values and the indices of a list we will use enumerate() which is a python built-in function.

It is to be noted that this method is one of the fastest and most efficient methods for acquiring the index in a for loop.

my_list = [1, 2, 7, 3, 5, 4, 2, 2, 5, 5]
print("Indices and values in my_list:")
for index, value in enumerate(my_list):
   print(list((index, value)))

Indices and values in my_list:

[0, 1] [1, 2] [2, 7] [3, 3] [4, 5] [5, 4] [6, 2] [7, 2] [8, 5] [9, 5]

How to use Numpy to get the index of an element in a list ?

We will use the np.where() method from the Numpy module to get the index of an element in a list.

import numpy as np
mylist = [1,2,3,4,5]
#Create a numpy array from a list of numbers
new_list = np.array(mylist)
np.where(new_list==3)

array([2],)

LEAVE A REPLY

Please enter your comment!
Please enter your name here