In Python, a list is a versatile data structure that can hold a collection of items. Lists are mutable, meaning their elements can be changed after the list is created. They are ordered, allowing you to access elements by their index. Python lists can contain elements of different data types, including integers, floats, strings, and even other lists (nested lists). Let's dive into the types and operations of lists in Python:
Basic Operations:
Creating Lists:
You can create a list by enclosing comma-separated values within square brackets [ ].
Input is Shown Below :
Code :
#Lists are mutable (we can update any elements inside the list
#list begin with [] brackets
#Code by IAH
a = ["apple","mango","banana","grapes"] #As we can see we have taken 5 words inside the list
print(a)
#The output will show print of the above list
Output is Shown Below :
2. Accessing Elements:
Elements in a list can be accessed using their index. Indexing starts from 0.
Input is Shown Below :
Code :
#Lists are mutable (we can update any elements inside the list
#list begin with [] brackets
#Code by IAH
a = ["apple","mango","banana","grapes"] #As we can see we have taken 5 words inside the list
# print(a)
print(a[0:2]) #this will print the list elements at specific index from 0 till last element of list
#The output will show print of the above list and its elements at specific index
Output is Shown Below :
3. Slicing:
You can extract a sub list (slice) from a list using the slice operator :.
Input is Shown Below :
Code :
#Lists are mutable (we can update any elements inside the list
#list begin with [] brackets
#Code by IAH
a = ["apple","mango","banana","grapes"] #As we can see we have taken 5 words inside the list
# Slicing from index 2 to the end
a1 = a[2:]
print("Slice 1:", a1)
# Slicing up to index 4 (not including index 4)
b1 = a[:4]
print("Slice 2:", b1)
# Slicing from index 1 to index 4 (not including index 4)
c1 = a[1:4]
print("Slice 3:", c1)
# Slicing with a step of 2 (taking every second element)
d1 = a[::2]
print("Slice 4:", d1)
# Reversing the list
e1 = a[::-1]
print("Slice 5:", e1)
#The output will show print of the above list various slices at various indexes
Output is Shown Below :
start_index: The index from which slicing begins (inclusive).end_index: The index at which slicing ends (exclusive).step (optional): The increment between each index.
If start_index is not specified, slicing starts from the beginning of the list. If end_index is not specified, slicing continues to the end of the list. If step is not specified, it defaults to 1.
Here's a breakdown:
- If you want all elements from the list starting from index 2:
list_name[2:] - If you want elements up to index 5 (but not including index 5):
list_name[:5] - If you want elements from index 2 to index 5 (but not including index 5):
list_name[2:5] - If you want every second element from the entire list:
list_name[::2] - If you want to reverse the list:
list_name[::-1]
4. Updating Elements:
Lists are mutable, so you can change the value of elements. To update an element inside a list in Python, you can simply assign a new value to the element at the desired index. Here's the syntax:
list_name[index] = new_value
Where:
list_name is the name of the list.index is the index of the element you want to update.new_value is the new value you want to assign to that element.
Here's an example:-
Input is Shown Below :
Code :
#Lists are mutable (we can update any elements inside the list
#list begin with [] brackets
#Code by IAH
a = ["apple","mango","banana","grapes"] #As we can see we have taken 5 words inside the list
a[2] = "orange" #to update any element we taken a list at
specific index 2
print("Original List: " ,a) #print the original list
print("Updated List : ",a) #print the updated list
#The output will show print of the above list updating at various indexes
In this example, the element at index 2 ("banana") is updated to "orange".
Output is Shown Below :
5. Adding Elements:
You can append elements to the end of a list using the append() method. Here is the syntax:
Input is Shown Below :
Code :
#Lists are mutable (we can update any elements inside the list
#list begin with [] brackets
#Code by IAH
a = ["apple","mango","banana","grapes"] #As we can see we have taken 5 words inside the list
a.append(2) #to add ant new number in element we require append command in list for numbers without double comma we can use
a.append("Kiwi") #to add ant new element in element we require append command in list for numbers with double comma we can use
print("Original List: " ,a)
print("Updated List : ",a)
#The output will show print of the above list various append (adding) at indexes
Output is Shown Below :
To insert an element at a specific position within the list, you can use the insert() method. Here's the syntax:
list_name.insert(index, new_element)
Where:
list_name is the name of the list.index is the position where you want to insert the new element.new_element is the element you want to insert into the list.
Here's an example:
Input is Shown Below :
Code :
#Lists are mutable (we can update any elements inside the list
#list begin with [] brackets
#Code by IAH
a = ["apple","mango","banana","grapes"] #As we can see we have taken 5 words inside the list
print("Original List : ",a)
# Insert a new element at index 1
a.insert(1, "date")
print("Updated List : " ,a)
#The output will show print of the above list adding element at specific index
Output is Shown Below :
In this example, "date" is inserted at index 1, shifting the original element at index 1 ("mango") and all subsequent elements to the right.
6. Removing Elements:
Elements can be removed using del statement or remove() method.
6.1. Using remove() Method:
This method removes the first occurrence of a specified value.
Input is Shown Below :
Code :
#Lists are mutable (we can update any elements inside the list
#list begin with [] brackets
#Code by IAH
a = ["apple","mango","banana","grapes"] #As we can see we have taken 5 words inside the list
a.remove("banana") # Removes the first occurrence of 3
print(a) # Output: ["apple", "mango" ,"grapes"]
#The output will show print of the above list removed elements
Output is Shown Below :
6. 2. Using del Statement:
You can remove an element using its index with the del statement.
Input is Shown Below :
Code :
#Lists are mutable (we can update any elements inside the list
#list begin with [] brackets
#Code by IAH
a = ["apple","mango","banana","grapes"] #As we can see we have taken 5 words inside the list
del a[3] # Removes the element at index 2 (i.e., "grapes")
print(a) # Output: ["apple", "mango" ,"banana"]
#The output will show print of the above list removed elements
Output is Shown Below :
7. Length of List:
You can find the number of elements in a list using the len() function.
Input is Shown Below :
Code :
#Lists are mutable (we can update any elements inside the list
#list begin with [] brackets
#Code by IAH
a = ["apple","mango","banana","grapes"] #As we can see we have taken 5 words inside the list
print(len(a)) #len(a) means length of the above list which is filled with 5 words so length will be 5
print(type(a)) #type function will tell type of function used which is list type so it will print that
#The output will show print of both type and length of the above list
Output is Shown Below :
This method removes and returns the element at the specified index. If no index is provided, it removes and returns the last element.
Input is Shown Below :
Code :
#Lists are mutable (we can update any elements inside the list
#list begin with [] brackets
#Code by IAH
a = ["apple","mango","banana","grapes"] #As we can see we have taken 5 words inside the list
a.pop(3) # Removes and returns the element at index 2 (i.e., grapes)
print(a) # Output: ["apple", "mango" ,"banana"]
#The output will show print of the above list popped elements
Output is Shown Below :
9. Using filter() Function:
The filter() function can also be used to filter out elements based on a condition.
Input is Shown Below :
Code :
#Lists are mutable (we can update any elements inside the list
#list begin with [] brackets
#Code by IAH
a = ["apple","mango","banana","grapes"] #As we can see we have taken 5 words inside the list
a = list(filter(lambda x: x != "banana", a)) # Removes all occurrences of banana word
print(a) # Output: ["apple", "mango" ,"grapes"]
#The output will show print of the above list removed occurrence of specific elements
Output is Shown Below :

Sorting elements in a list in Python is a common operation and can be done in various ways. Let's explore some of the methods available:
10. Using sorted() Function:
The sorted() function returns a new sorted list from the elements of any iterable object (including lists). It doesn't modify the original list.
Input is Shown Below:
Code :
#Lists are mutable (we can update any elements inside the list
#list begin with [] brackets
#Code by IAH
a = ["apple","mango","banana","grapes"] #As we can see we have taken 5 words inside the list
sorted_list = sorted(a) #It will does the sorting of the list in ascending order
print("Sorted List = ",sorted_list) # Output: ['apple','banana','grapes'.'mango']
print("Original List =",a) # Output: ["apple", "mango" ,"grapes"]
#The output will show print of the above list in sorted manner
Output is Shown Below :
10.2.Using sort() Method:
The sort() method sorts the list in place, modifying the original list.
Input is Shown Below :
Code :
#Lists are mutable (we can update any elements inside the list
#list begin with [] brackets
#Code by IAH
a = ["apple","mango","banana","grapes"] #As we can see we have taken 5 words inside the list
a.sort() #It will does the sorting of the list in ascending order
print("Sorted List = ",a) # Output: ['apple','banana','grapes'.'mango']
#The output will show print of the above list in sorted manner
Output is Shown Below :
10.3.Custom Sorting with key Parameter:
Both sorted() and sort() functions accept a key parameter which allows you to specify a function to be called on each list element before making comparisons. This is useful for sorting objects based on specific attributes or criteria.
Input is Shown Below :
Code :
#Lists are mutable (we can update any elements inside the list
#list begin with [] brackets
#Code by IAH
a = ["apple","mango","banana","grapes"] #As we can see we have taken 5 words inside the list
sorted_list = sorted(a,key=len) # Sorts based on length
print("Sorted List = ",sorted_list) # Output: ['apple','banana','grapes'.'mango']
#The output will show print of the above list in sorted manner
Output is Shown Below :
10.4.Sorting in Reverse Order:
You can specify reverse=True parameter to sort the list in descending order.
Input is Shown Below :
Code :
#Lists are mutable (we can update any elements inside the list
#list begin with [] brackets
#Code by IAH
a = ["apple","mango","banana","grapes"] #As we can see we have taken 5 words inside the list
sorted_list = sorted(a, reverse=True)
print("Reverse Sorted List = ",sorted_list) # Output: ['apple','banana','grapes'.'mango']
#The output will show print of the above list in reverse sorted manner
Output is Shown Below :
10.5.Sorting Complex Objects:
For sorting a list of complex objects (e.g., dictionaries, custom classes), you can use the key parameter to specify a function that extracts the key for comparison.
Input is Shown Below :
Code :
#Lists are mutable (we can update any elements inside the list
#list begin with [] brackets
#Code by IAH
students = [ #As we can see we have taken some words inside the list
{'name': 'Alice', 'grade': 90},
{'name': 'Bob', 'grade': 85},
{'name': 'Charlie', 'grade': 88}
]
sorted_students = sorted(students, key=lambda x: x['grade'], reverse=True)
# Output: [{'name': 'Alice', 'grade': 90}, {'name': 'Charlie', 'grade': 88}, {'name': 'Bob', 'grade': 85}]
print("Reverse Sorted List = ",sorted_students)
#The output will show print of the above list in reverse sorted manner
Output is Shown Below :
Comments
Post a Comment