Python

List in Python

Click for All Topics

List in Python

A list is a data structure used to store collections. It contains elements of different data types, such as integers, floats, strings and other data types also.

Properties of List:

1.) Indexable, index starts from 0

2.) Mutable i.e. we can change , add and remove values inside the list.

3.) Can contain dissimilar data types.

4.) Duplicates allowed.

Accessing elements in List
Printing the whole list :
				
					l = ['apple','mango','banana']
print(l) #print(name_of_the_list)

# OUTPUT:
# ['apple','mango','banana']
				
			
Accessing Specific elements of List

You can access specific elements from list by specifying the index of that element

list[index]

For example, consider the following list:

				
					fruits = ['apple', 'banana', 'orange', 'kiwi', 'grape']
     #  [   0   ,     1   ,     2    ,   3  ,     4   ]     # index corrosponds
                                                                                                                        # to each elements
print(fruits[0])      #will give output    apple
print(fruits[4])      #will give output    grape
				
			
Negative Indexing:

In Python, negative indexing is a way to access elements from the end of a list. The last element has an index of -1, the second last has an index of -2, and so on.

				
					fruits = ['apple', 'banana', 'orange', 'kiwi', 'grape']
     #  [   0   ,     1   ,     2    ,   3  ,     4   ]     # index corrosponds
     #  [  -5   ,    -4   ,    -3    ,  -2  ,    -1   ]     # negative indexing                                                                                                                   # to each elements

print(fruits[4])      #will give output   grape
print(fruits[-1])     #will give output   grape
				
			
Slicing in List:

Slicing in a list means accessing a specific range of elements from the list. It is done by defining the starting and ending index of the range to be accessed.

 

💡: Value at the last index is excluded

				
					fruits = ['apple', 'banana', 'orange', 'kiwi', 'grape']
     #  [   0   ,     1   ,     2    ,   3  ,     4   ]     # index corrosponds
                                                                                                                        # to each elements
print(fruits[2:4])     # output will be ['orange', 'kiwi']
                       # you can see , grape is not in the output list, because last
                       # index(4 in this case) is excluded
				
			
Iteration in list:

To process each element in list ,we have to iterate the list

Using while loop

				
					fruits = ['apple', 'banana', 'orange', 'kiwi', 'grape']
i = 0
while i < len(fruits):        #len(list) return the length of list
    print(fruits[i])
    i += 1
    
# Output
# apple
# banana
# orange
# kiwi
# grape
				
			

Using for loop

				
					fruits = ['apple', 'banana', 'orange', 'kiwi', 'grape']
for i in fruits:
    print(i)
    
# Output
# apple
# banana
# orange
# kiwi
# grape
				
			

Concatenation and merging of list

Concatenation is appending a new list on a list while merging is to merge 2 (or more) list to create a third list

				
					# Concatenation
l1 = [1,2,3]
l1 = l1 + [4,5,6]
print(l1)

# output :-
# [1,2,3,4,5,6]


# merging
l1 = [1,2,3]
l2 = [4,5,6]
l3 = l1 + l2
print(l3)

# output
# [1,2,3,4,5,6]
				
			

Searching and Sorting in list:

There are some built-in methods in python for searching elements and for ordering (ascending or descending) the list

				
					# searching  Method 1
l1 = [1,2,3,4]
print(l1.index(3))

# output
# 2
# index function will return the index value of the element where the number 3 is present

# searching  Method 2 
# To check only if perticular value is present in a list or not

l1 = [1,2,3,4]
a = 1 in l1          # using membership to return boolean value
b = 5 in l1
print(a)
print(b)

# output
# True
# False
				
			

Sorting in list

				
					l1 = [5,3,2,1,4,6]
print(sorted(l1))     # [1,2,3,4,5,6]
print(l1)             # [5,3,2,1,4,6]
print(l1.sort())      # None
print(l1)             # [1,2,3,4,5,6]
				
			

💡 sort will change the original list while sorted() will create a new list and do not modify the original list

Reverse a list

				
					# Method 1     using sort and reverse
l = [1,5,3,2,4,6]
l.reverse()
print(l)                   #[6,4,2,3,5,1]
l.sort(reverse = True)     
print(l)                   #[6,5,4,3,2,1]

# Method 2      using sorted and reversed
print(list(reversed(l)))          #[1,2,3,4,5,6]
print(sorted(l,reverse = True))   #[6,5,4,3,2,1]


# Method 3     using slicing operator
print(l[::-1])              #[1,2,3,4,5,6]
				
			

💡Note: reversed() function returns an iterator object which have to be converted into list , tupple, string , set , as per your requirement

List Methods

1.) list.append() : To place more elements at the end of the list
				
					l=[1,2,3,4,5]
print(l)
l.append(6)
print(l)

# Output -
# [1,2,3,4,5]
# [1,2,3,4,5,6]
				
			
2.) list.remove()

To remove any element from a list

				
					l = [1,2,3,4]
l.remove(3)
print(l)

# Output
# [1,2,4]
				
			

💡 reports value error if value is not present in the list

💡 If there are more then one occurrence of an element , only 1st occurrence will be deleted

3.) list.pop()

To remove the last element from the list

If you give index as an argument if this method, value at that particular index will remove

				
					l = [1,2,3,4]
l.pop()
print(l)    # [1,2,3]
l.pop(0)
print(l)    # [2,3]
				
			

💡In case of pop you have to pass the index of the value you have to delete

💡In case of remove you have to pass the value which you have to remove

4.) list.count()

To count the number of occurrence of an element in list

				
					l = [1,1,2,3,4,4,5,4]
print(l.count(4))

# output
# 3
				
			
5.) list.index()

we use .index() method to find the index of element present in list

				
					l = [1,2,3,4]
print(l.index(2))

# output
# 3
				
			
6.) list.insert()

To insert an element in a list at a particular index

we have to pass index and value as argument inside insert

				
					l = [1,2,3]
l.insert(2,9)
print(l)

# output
# [1,2,9,3]
				
			
7.) list.clear()

Removes all the elements from the list

				
					l = [1,2,3,4,5,6]
l.clear()
print(l)      

# output
# []
				
			
8.) list.copy()

Returns a copy of the list

				
					l = [1,2,3,4,5,6]
l2 = l.copy()
print(l2)      # output:[1,2,3,4,5,6]
				
			
9.) list1.extend(list2)
				
					# Method 1 for extending list
l1 = [1,2,3]
l2 = [4,5,6]
l1.extend(l2)
print(l1)

# output
# [1,2,3,4,5,6]


# Method 2 for extending list
l2 = [4,5,6]
l = [1,2,3,*l2]
print(l)

# output:
# [1,2,3,4,5,6]
				
			

Built-in functions in list

1.) len(list)

Returns the number of items in a list

2.) max(list)

Returns the max element in a list

3.) min(list)

Returns the number of items in a list

4.) sum(list)

Returns the number of all the elements in a list

5.) any(list)

Returns the number of items in a list

6.) all(list)

Returns the number of items in a list