Intensity Coding
  • HOME
  • TUTORIALS
    • Python
    • Natural Language Processing
    • Generative AI
  • ABOUT US
    • About Us
    • Contact Us
    • Privacy Policy
    • Terms and Conditions
    • Disclaimer

Python

Python Lists

Python
Python
  • Introduction To Python
  • Write Your First Python Program
  • Indentation And Comments in Python
  • Variables in Python
  • Data Types in Python
  • Booleans and Number in Python
  • Operators in Python
  • Mutable Vs Immutable Objects And Collection in Python
  • Python String
  • Python Lists
  • Python Tuples
  • Python Sets
  • Python Dictionaries
  • Python Control Statements
  • Python Functions
  • Python Lambda Functions
  • Python Exception Handling
  • Python File Handling
  • Python Package and PIP
  • Python Modules
  • Python Keywords
  • Python Built In Method
  • Python Regular Expressions (RegEx)
  • Python JSON
  • Python Datetime

Python Lists¶

Introduction of Lists¶

  • A list is a data structure in Python that allows storing multiple items in a single variable.
  • Python provides four built-in collection types: List, Tuple, Set, and Dictionary, each with unique characteristics.
  • Lists are ordered, mutable (modifiable), and can contain duplicate elements.
  • Indexing starts at 0, meaning the first item is at position 0, the second at 1, and so on.
  • The order of items remains consistent unless explicitly modified. New elements added to a list appear at the end.
  • Since lists are mutable, items can be added, removed, or updated after creation.
  • The len() function is used to determine the number of elements in a list.
In [ ]:
mylist = ["Intensity", "Coding", "Python", "Intensity"]
print(mylist)
print(len(mylist))
['Intensity', 'Coding', 'Python', 'Intensity']
4

List Items - Different Data Types¶

  • A list can store elements of the same or different data types:
In [ ]:
list1 = ["Intensity", "Coding", "Python"]  # String elements
list2 = [10, 20, 30, 40]  # Integer elements
list3 = [True, False, True]  # Boolean values
list4 = ["Data", 25, True, 3.14, "ML"]  # Mixed data types

Checking List Type¶

  • In Python, lists are internally recognized as objects of type list.
In [ ]:
mylist = ["Intensity", "Coding", "Python"]
print(type(mylist))  # Output: <class 'list'>
<class 'list'>

Creating a List Using list() Constructor¶

  • Instead of using square brackets [], lists can also be created using the list() constructor.
In [ ]:
mylist = list(("Intensity", "Coding", "Python"))  # Notice the double parentheses
print(mylist)
['Intensity', 'Coding', 'Python']

Basic List Operations¶

Python Expression Output Description
len(["Intensity", "Coding", "Python"]) 3 Returns the number of elements
["Intensity", "Coding"] + ["Python", "AI"] ["Intensity", "Coding", "Python", "AI"] Concatenation
["ML"] * 3 ["ML", "ML", "ML"] Repeats elements
"Coding" in ["Intensity", "Coding", "Python"] True Membership test
for x in ["Intensity", "Coding", "AI"]: print(x, end=" ") Intensity Coding AI Iteration

Finding Maximum and Minimum Values¶

max() Function¶

The max() function retrieves the largest element in a list.

In [ ]:
list1 = ["Intensity", "Coding", "Python", "AI"]
list2 = [12, 45, 78, 23, 56]

print("Max value element in list1:", max(list1))  # Based on lexicographic order
print("Max value element in list2:", max(list2))  # Based on numerical value
Max value element in list1: Python
Max value element in list2: 78

min() Function¶

  • The min() function retrieves the smallest element in a list.
In [ ]:
list1 = ["Intensity", "Coding", "Python", "AI"]
list2 = [12, 45, 78, 23, 56]

print("Min value element in list1:", min(list1))  # Based on lexicographic order
print("Min value element in list2:", min(list2))  # Based on numerical value
Min value element in list1: AI
Min value element in list2: 12

Accessing Elements in a List¶

  • Lists store elements sequentially, allowing access using their index positions.
  • The first item is located at index 0.
  • Negative indexing enables retrieval from the end of the list, where -1 represents the last element, -2 the second last, and so forth.
In [ ]:
data_list = ["Intensity", "Coding", "Python"]
print(data_list[1])   # Output: Coding
print(data_list[-1])  # Output: Python
Coding
Python

Selecting a Range of Elements¶

  • You can extract a subset of elements using a range of indexes.
  • The resulting output is a new list containing the selected elements.
  • The slicing starts from index 2 (inclusive) and stops at index 5 (exclusive).
  • Omitting the start index includes all elements from the beginning.
  • Omitting the end index includes elements until the end of the list.
In [ ]:
data_list = ["Intensity", "Coding", "Python", "AI", "ML", "Deep Learning", "NLP"]

print(data_list[2:5])   # Output: ['Python', 'AI', 'ML']
print(data_list[:4])    # Output: ['Intensity', 'Coding', 'Python', 'AI']
print(data_list[2:])    # Output: ['Python', 'AI', 'ML', 'Deep Learning', 'NLP']
print(data_list[-4:-1]) # Output: ['AI', 'ML', 'Deep Learning']
print(data_list * 2)    # Duplicates the list elements
['Python', 'AI', 'ML']
['Intensity', 'Coding', 'Python', 'AI']
['Python', 'AI', 'ML', 'Deep Learning', 'NLP']
['AI', 'ML', 'Deep Learning']
['Intensity', 'Coding', 'Python', 'AI', 'ML', 'Deep Learning', 'NLP', 'Intensity', 'Coding', 'Python', 'AI', 'ML', 'Deep Learning', 'NLP']

Verifying if an Item Exists in a List¶

  • The in keyword checks for an element’s presence within a list.
In [ ]:
data_list = ["Intensity", "Coding", "Python"]

if "Intensity" in data_list:
    print("Yes, 'Intensity' is in the list")
Yes, 'Intensity' is in the list

Modifying List Items¶

Updating a Specific Item¶

  • To modify a particular item in a list, use its index number:
In [ ]:
thislist = ["low", "medium", "high"]
thislist[1] = "intensity coding"
print(thislist)
['low', 'intensity coding', 'high']

Changing a Range of Items¶

  • You can update multiple items at once by assigning a new list to a specific range of indices.

  • If more items are added than replaced, the list expands.

  • If fewer items are added, the list shrinks.

  • The total length of the list adjusts accordingly.

In [ ]:
thislist = ["low", "medium", "high", "extreme", "peak"]
thislist[1:3] = ["intensity coding", "ultra"]
print(thislist)

thislist = ["low", "medium", "high"]
thislist[1:2] = ["intensity coding", "ultra"]
print(thislist)

thislist = ["low", "medium", "high"]
thislist[1:3] = ["intensity coding"]
print(thislist)
['low', 'intensity coding', 'ultra', 'extreme', 'peak']
['low', 'intensity coding', 'ultra', 'high']
['low', 'intensity coding']

Inserting New Items Without Replacing Existing Ones¶

  • To add an item at a specific position without removing any existing elements, use the insert() method:
In [ ]:
thislist = ["low", "medium", "high"]
thislist.insert(2, "intensity coding")
print(thislist)
['low', 'medium', 'intensity coding', 'high']

Removing Items from a List¶

Removing a Specific Item¶

  • The remove() method eliminates a specific item from the list.
In [ ]:
thislist = ["low", "medium", "intensity coding", "high"]
thislist.remove("intensity coding")
print(thislist)
['low', 'medium', 'high']

Removing an Item by Index¶

  • The pop() method removes an element at a given index.
  • If no index is provided, it removes the last item by default.
In [ ]:
thislist = ["low", "medium", "intensity coding", "high"]
thislist.pop(2)
print(thislist)
['low', 'medium', 'high']
In [ ]:
thislist = ["low", "medium", "intensity coding", "high"]
thislist.pop()
print(thislist)
['low', 'medium', 'intensity coding']

Using the del Keyword¶

  • The del keyword removes an item at a specific position.
  • It can also be used to delete the entire list.
In [ ]:
thislist = ["low", "medium", "intensity coding", "high"]
del thislist[2]
print(thislist)
['low', 'medium', 'high']
In [ ]:
thislist = ["low", "medium", "intensity coding", "high"]
del thislist

Clearing All Items from a List¶

  • The clear() method removes all elements, leaving an empty list.
In [ ]:
thislist = ["low", "medium", "intensity coding", "high"]
thislist.clear()
print(thislist)
[]

Iterating Over Lists¶

Standard Looping Through a List¶

In [ ]:
# Loop through each element in thislist and print it
thislist = ["intensity", "coding", "power"]
for element in thislist:
    print(element)
intensity
coding
power

Looping with Index References¶

In [ ]:
# Loop through thislist using index values and print each element
thislist = ["intensity", "coding", "power"]
for index in range(len(thislist)):
    print(thislist[index])
intensity
coding
power

Using a While Loop for Iteration¶

In [ ]:
# Use a while loop to iterate through thislist and print each element
thislist = ["intensity", "coding", "power"]
index = 0
while index < len(thislist):
    print(thislist[index])
    index += 1  # Increment index to move to the next element
intensity
coding
power

List Comprehension for Compact Iteration¶

In [ ]:
# Use list comprehension to iterate through thislist and print each element
thislist = ["intensity", "coding", "power"]
[print(element) for element in thislist]
intensity
coding
power
Out[ ]:
[None, None, None]

Merging Lists¶

Using the + Operator¶

  • One of the simplest ways to combine lists is by utilizing the + operator, which creates a new list by appending elements from both lists.
In [ ]:
list1 = ["a", "b", "c"]
list2 = [1, 2, 3]

list3 = list1 + list2  # Merging lists using +
print(list3)  # Output: ['a', 'b', 'c', 1, 2, 3]
['a', 'b', 'c', 1, 2, 3]

Appending Elements One by One¶

  • We can also merge lists by appending each element from list2 into list1 using a loop.
In [ ]:
list1 = ["a", "b", "c"]
list2 = [1, 2, 3]

for item in list2:
    list1.append(item)  # Appending each element one by one

print(list1)  # Output: ['a', 'b', 'c', 1, 2, 3]
['a', 'b', 'c', 1, 2, 3]

Using the extend() Method¶

  • The extend() method is a direct and efficient way to append all elements of list2 into list1.
In [ ]:
list1 = ["a", "b", "c"]
list2 = [1, 2, 3]

list1.extend(list2)  # Efficiently merging lists with extend()
print(list1)  # Output: ['a', 'b', 'c', 1, 2, 3]
['a', 'b', 'c', 1, 2, 3]

Copying Lists¶

  • Assigning a list to another variable using = does not create a new list; instead, both variables reference the same list in memory.
  • Any modification made to one list will affect the other.
In [ ]:
fruits = ["mango", "grape", "kiwi"]
new_fruits = fruits  # Both variables point to the same list

fruits.append("pineapple")  # Modifying the original list

print(new_fruits) # Output: ['mango', 'grape', 'kiwi', 'pineapple']
['mango', 'grape', 'kiwi', 'pineapple']

Copying a List Using copy() Method¶

  • The copy() method creates an independent copy, ensuring changes in one do not affect the other.
In [ ]:
fruits = ["mango", "grape", "kiwi"]
new_fruits = fruits.copy()  # Creates a separate copy

fruits.append("pineapple")  # Changes in original list do not affect new_fruits
print(new_fruits)  # Output: ['mango', 'grape', 'kiwi']
['mango', 'grape', 'kiwi']

Copying a List Using list() Constructor¶

  • The list() constructor provides another way to copy a list, creating a new independent instance.
In [ ]:
fruits = ["mango", "grape", "kiwi"]
new_fruits = list(fruits)  # Creates a new copy using list()

fruits.append("pineapple")  # Changes in original list do not affect new_fruits
print(new_fruits)  # Output: ['mango', 'grape', 'kiwi']
['mango', 'grape', 'kiwi']

Sorting Lists¶

Sorting a List Alphanumerically¶

  • Lists have a built-in sort() method that arranges elements in ascending order by default.
  • Strings are sorted lexicographically, while numbers are arranged in increasing order.
In [ ]:
# Sorting a list of strings in ascending order
cities = ["Berlin", "Tokyo", "New York", "Sydney", "London"]
cities.sort()
print(cities)  # Output: ['Berlin', 'London', 'New York', 'Sydney', 'Tokyo']

# Sorting a list of numbers in ascending order
scores = [88, 42, 75, 96, 19]
scores.sort()
print(scores)  # Output: [19, 42, 75, 88, 96]
['Berlin', 'London', 'New York', 'Sydney', 'Tokyo']
[19, 42, 75, 88, 96]

Sorting in Descending Order¶

  • Use reverse=True in the sort() method to arrange elements in descending order.
In [ ]:
# Sorting a list of strings in descending order
cities = ["Berlin", "Tokyo", "New York", "Sydney", "London"]
cities.sort(reverse=True)
print(cities)  # Output: ['Tokyo', 'Sydney', 'New York', 'London', 'Berlin']

# Sorting a list of numbers in descending order
scores = [88, 42, 75, 96, 19]
scores.sort(reverse=True)
print(scores)  # Output: [96, 88, 75, 42, 19]
['Tokyo', 'Sydney', 'New York', 'London', 'Berlin']
[96, 88, 75, 42, 19]

Custom Sorting with a Function¶

  • The key parameter allows defining custom sorting criteria using a function.

  • This function determines how elements are ordered.

In [ ]:
# Sorting numbers based on their distance from 70
def distance_from_seventy(n):
    return abs(n - 70)

scores = [88, 42, 75, 96, 19]
scores.sort(key=distance_from_seventy)
print(scores)  # Output: [75, 88, 42, 96, 19] (Sorted by proximity to 70)
[75, 88, 96, 42, 19]

Case-Insensitive Sorting¶

  • By default, sorting considers uppercase letters before lowercase.

  • Use str.lower as the key function to perform case-insensitive sorting.

In [ ]:
# Case-sensitive sorting
languages = ["Python", "java", "C++", "Go", "ruby"]
languages.sort()
print(languages)  # Output: ['C++', 'Go', 'Python', 'java', 'ruby'] (Uppercase comes first)

# Case-insensitive sorting
languages = ["Python", "java", "C++", "Go", "ruby"]
languages.sort(key=str.lower)
print(languages)  # Output: ['C++', 'Go', 'java', 'Python', 'ruby']
['C++', 'Go', 'Python', 'java', 'ruby']
['C++', 'Go', 'java', 'Python', 'ruby']

Reversing List Order¶

  • The reverse() method reverses the order of elements without sorting.
In [ ]:
languages = ["Python", "java", "C++", "Go", "ruby"]
languages.reverse()
print(languages)  # Output: ['ruby', 'Go', 'C++', 'java', 'Python']
['ruby', 'Go', 'C++', 'java', 'Python']

List Comprehension¶

  • List comprehension provides a concise way to create new lists by transforming or filtering elements from an existing iterable.

Why Use List Comprehension?¶

  • It offers a more readable and compact syntax compared to traditional for loops.
  • It allows filtering elements based on conditions.
  • It creates a new list without modifying the original one.

Syntax¶

newlist = [expression for item in iterable if condition]
  • Expression → Defines the transformation or outcome of each element.

  • Iterable → Any sequence like a list, tuple, set, or range.

  • Condition (Optional) → Acts as a filter to include only specific elements.

Filtering Elements with List Comprehension¶

In [ ]:
# Filtering words that contain the letter 'e'
words = ["desk", "laptop", "phone", "tablet", "mouse"]
filtered_list = [word for word in words if "e" in word]
print(filtered_list)
# Output: ['desk', 'tablet', 'mouse']

# Equivalent traditional for loop approach
filtered_list = []
for word in words:
    if "e" in word:
        filtered_list.append(word)
print(filtered_list)
# Output: ['desk', 'tablet', 'mouse']
['desk', 'phone', 'tablet', 'mouse']
['desk', 'phone', 'tablet', 'mouse']

Excluding Specific Elements¶

In [ ]:
# Creating a list excluding a specific item
devices = ["phone", "laptop", "tablet", "monitor"]
filtered_list = [item for item in devices if item != "laptop"]
print(filtered_list)
# Output: ['phone', 'tablet', 'monitor']
['phone', 'tablet', 'monitor']

Using List Comprehension Without Filtering¶

In [ ]:
# Copying a list using list comprehension
devices = ["phone", "laptop", "tablet", "monitor"]
copied_list = [item for item in devices]
print(copied_list)
# Output: ['phone', 'laptop', 'tablet', 'monitor']
['phone', 'laptop', 'tablet', 'monitor']

Using an Iterable Object in List Comprehension¶

  • The iterable can be any sequence such as a list, range, or tuple.
In [ ]:
# Generating a list of numbers from 0 to 9
numbers = [x for x in range(10)]
print(numbers)  # Output: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

# Generating numbers less than 5
numbers = [x for x in range(10) if x < 5]
print(numbers)  # Output: [0, 1, 2, 3, 4]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
[0, 1, 2, 3, 4]

Modifying Elements with Expressions¶

  • The expression in list comprehension can modify each element before adding it to the new list.
In [ ]:
# Converting all words to uppercase
devices = ["phone", "laptop", "tablet", "monitor"]
uppercase_list = [device.upper() for device in devices]
print(uppercase_list)
# Output: ['PHONE', 'LAPTOP', 'TABLET', 'MONITOR']
['PHONE', 'LAPTOP', 'TABLET', 'MONITOR']

Replacing Elements with a Fixed Value¶

In [ ]:
# Replacing all elements with a fixed value
devices = ["phone", "laptop", "tablet", "monitor"]
new_list = ["available" for item in devices]
print(new_list)
# Output: ['available', 'available', 'available', 'available']
['available', 'available', 'available', 'available']

Conditional Expressions in List Comprehension¶

In [ ]:
# If an item is 'tablet', replace it with 'smartwatch'; otherwise, keep the original value.
devices = ["phone", "laptop", "tablet", "monitor"]
updated_list = [item if item != "tablet" else "smartwatch" for item in devices]
print(updated_list)
# Output: ['phone', 'laptop', 'smartwatch', 'monitor']
['phone', 'laptop', 'smartwatch', 'monitor']

Python - List Methods¶

List Methods in Python¶

No. Method Description
1 append() Adds an element at the end of the list.
2 clear() Removes all the elements from the list.
3 copy() Returns a shallow copy of the list.
4 count() Returns the number of occurrences of a specified value.
5 extend() Adds the elements of an iterable to the end of the list.
6 index() Returns the index of the first occurrence of a specified value.
7 insert() Inserts an element at a specified position.
8 pop() Removes and returns the element at a specified position (default is last).
9 remove() Removes the first occurrence of a specified value.
10 reverse() Reverses the order of the list in place.
11 sort() Sorts the list in ascending order (or based on a custom function).

1. append()¶

Point Description
Use Case The append() method adds an element to the end of the list. It modifies the original list in place.
Syntax list.append(elmnt)
Parameter elmnt (Required) — The element to be added to the list. Can be of any data type (string, number, object, list, etc.).

Useful Information¶

No. Point Description
1 Modifies the Original List The method alters the list instead of returning a new one.
2 Accepts Any Data Type The appended element can be a string, number, object, or another list.
3 Appends as a Single Element If a list is appended, it is added as a single item, not merged with the existing list.
4 Increases List Length The length of the list increases by 1 for each appended element.
5 Does Not Return a Value The method does not return a new list; it updates the existing one.
In [ ]:
# Append a single string element to the list
items = ['intensity', 'coding', 'python']
items.append("tutorial")
print(items)  # Output: ['intensity', 'coding', 'python', 'tutorial']

# Append a list as a single element
a = ["backend", "development", "API"]
b = ["database", "Django", "Flask"]
a.append(b)
print(a)  # Output: ['backend', 'development', 'API', ['database', 'Django', 'Flask']]
['intensity', 'coding', 'python', 'tutorial']
['backend', 'development', 'API', ['database', 'Django', 'Flask']]

2. clear()¶

Point Description
Use Case The clear() method removes all elements from a list, making it empty.
Syntax list.clear()
Parameter None

Useful Information¶

No. Point Description
1 Modifies the Original List The method clears the list in place instead of creating a new one.
2 Results in an Empty List After using clear(), the list remains but contains no elements.
3 Works on Any List Type It can be used on lists containing any data types.
4 Does Not Return a Value The method does not return a new list, only modifies the existing one.
5 Alternative Using Slicing The same effect can be achieved using list[:] = [].
In [ ]:
# List of popular programming languages
languages = ['Python', 'Java', 'C++', 'JavaScript']

# Clearing all elements from the list
languages.clear()

# The list is now empty
print(languages)  # Output: []
[]

Using Slicing ([:] = [])¶

In [ ]:
# List of web technologies
web_tech = ['HTML', 'CSS', 'JavaScript', 'React']

# Clearing the list using slicing
web_tech[:] = []

# The list is now empty
print(web_tech)  # Output: []
[]

3. copy()¶

Point Description
Use Case The copy() method creates a shallow copy of a list, preserving the original list.
Syntax new_list = list.copy()
Parameter None

Useful Information¶

No. Point Description
1 Creates a Shallow Copy Copies only references to nested elements, not deep copies.
2 Original List Remains Unchanged The copied list can be modified without affecting the original.
3 Alternative Method: Slicing ([:]) Using [:] achieves the same result as copy().
4 Does Not Work on Nested Lists For deeply nested lists, use copy.deepcopy() from the copy module.
5 Faster Than Manual Iteration The copy() method is optimized for list duplication.
In [ ]:
# Creating a list of programming-related words
concepts = ["intensity", "coding", "python"]

# Creating a copy using copy()
concepts_copy = concepts.copy()

# Modifying the copied list
concepts_copy.append("tutorial")

# Original list remains unchanged
print(concepts)       # Output: ['intensity', 'coding', 'python']
print(concepts_copy)  # Output: ['intensity', 'coding', 'python', 'tutorial']
['intensity', 'coding', 'python']
['intensity', 'coding', 'python', 'tutorial']

Copying a List Using Slicing¶

In [ ]:
# Using slicing to copy a list
frameworks = ["Django", "Flask", "FastAPI"]
frameworks_copy = frameworks[:]

# Adding an element to the copied list
frameworks_copy.append("Pyramid")

# Original list remains unaffected
print(frameworks)       # Output: ['Django', 'Flask', 'FastAPI']
print(frameworks_copy)  # Output: ['Django', 'Flask', 'FastAPI', 'Pyramid']
['Django', 'Flask', 'FastAPI']
['Django', 'Flask', 'FastAPI', 'Pyramid']

Copying Nested Lists (Shallow Copy)¶

In [ ]:
# Creating a nested list with backend and frontend stacks
tech_stack = [["Django", "Flask"], ["React", "Vue"]]

# Creating a shallow copy
shallow_copy = tech_stack.copy()

# Modifying an inner list
shallow_copy[0].append("FastAPI")

# Both lists are affected (shallow copy issue)
print(tech_stack)    # Output: [['Django', 'Flask', 'FastAPI'], ['React', 'Vue']]
print(shallow_copy)  # Output: [['Django', 'Flask', 'FastAPI'], ['React', 'Vue']]
[['Django', 'Flask', 'FastAPI'], ['React', 'Vue']]
[['Django', 'Flask', 'FastAPI'], ['React', 'Vue']]

Deep Copy Example (Fixing Shallow Copy Issues)¶

In [ ]:
import copy

# Creating a nested list with machine learning libraries
ml_libraries = [["TensorFlow", "PyTorch"], ["Scikit-learn", "Keras"]]

# Creating a deep copy
deep_copy = copy.deepcopy(ml_libraries)

# Modifying an inner list
deep_copy[0].append("JAX")

# Only deep_copy is affected
print(ml_libraries)  # Output: [['TensorFlow', 'PyTorch'], ['Scikit-learn', 'Keras']]
print(deep_copy)     # Output: [['TensorFlow', 'PyTorch', 'JAX'], ['Scikit-learn', 'Keras']]
[['TensorFlow', 'PyTorch'], ['Scikit-learn', 'Keras']]
[['TensorFlow', 'PyTorch', 'JAX'], ['Scikit-learn', 'Keras']]

4. count()¶

Point Description
Use Case The count() method returns the number of times a specified value appears in a list.
Syntax list.count(value)
Parameter value (Required) — The element to be counted (can be a string, number, list, tuple, etc.).

Useful Information¶

No. Point Description
1 Returns an Integer The method returns the number of times a given value occurs in the list.
2 Works with Various Data Types The value to count can be a string, number, or any hashable object.
3 Case-Sensitive When counting strings, "Python" and "python" are considered different.
4 Does Not Modify the List The method only returns the count; it does not change the list.
5 Can Be Used with Nested Lists If a list is inside another list, it counts as a single element.
In [ ]:
# Counting occurrences of a string
topics = ["intensity", "coding", "tutorial", "intensity"]
count_intensity = topics.count("intensity")
print(count_intensity)  # Output: 2
2

Counting Numbers in a List¶

In [ ]:
# Counting occurrences of a number
numbers = [1, 2, 3, 4, 2, 2, 5, 6, 2]
count_twos = numbers.count(2)
print(count_twos)  # Output: 4
4

Counting Elements in a Nested List¶

In [ ]:
# Nested lists count as a single element
nested_list = [["intensity", "coding"], ["tutorial"], "intensity"]
count_nested = nested_list.count(["intensity", "coding"])
print(count_nested)  # Output: 1
1

5. extend()¶

Point Description
Use Case The extend() method adds elements of an iterable (e.g., list, tuple, set) to the end of the current list.
Syntax list.extend(iterable)
Parameter iterable (Required) — Any iterable (list, set, tuple, etc.) whose elements will be added to the list.

Useful Information¶

No. Point Description
1 Modifies the Original List The method updates the existing list instead of creating a new one.
2 Accepts Any Iterable Lists, tuples, sets, and even strings can be used as input.
3 Elements Are Added Individually Unlike append(), which adds a list as a single element, extend() adds elements one by one.
4 Increases List Length The final list length is the sum of its original length and the added elements.
5 Works with Different Data Types The list can be extended with numbers, strings, or mixed data types.
In [ ]:
# Extending a list with another list
topics = ["intensity", "coding"]
new_topics = ["tutorial", "python"]
topics.extend(new_topics)
print(topics)  # Output: ['intensity', 'coding', 'tutorial', 'python']

# Extending a list with a tuple
frameworks = ["Django", "Flask"]
other_frameworks = ("FastAPI", "Pyramid")
frameworks.extend(other_frameworks)
print(frameworks)  # Output: ['Django', 'Flask', 'FastAPI', 'Pyramid']

# Extending a list with a set
languages = ["Python", "JavaScript"]
additional_languages = {"Go", "Rust"}
languages.extend(additional_languages)
print(languages)  # Output: ['Python', 'JavaScript', 'Go', 'Rust']

# Extending a list with characters from a string
letters = ["A", "B"]
letters.extend("CD")
print(letters)  # Output: ['A', 'B', 'C', 'D']
['intensity', 'coding', 'tutorial', 'python']
['Django', 'Flask', 'FastAPI', 'Pyramid']
['Python', 'JavaScript', 'Rust', 'Go']
['A', 'B', 'C', 'D']

6. index()¶

Point Description
Use Case The index() method returns the index of the first occurrence of the specified element in the list. If the element is not found, it raises a ValueError.
Syntax list.index(elmnt, start, end)
Parameter elmnt (Required) — The element to search for. Must be present in the list.
start (Optional) — The position to start searching from.
end (Optional) — The position to stop searching.

Useful Information¶

No. Point Description
1 Returns First Match Only Finds the first occurrence of the element and returns its index.
2 Raises an Error if Not Found If the element does not exist, a ValueError is raised.
3 Search Can Be Limited Optional start and end parameters can narrow down the search range.
4 Works with Different Data Types Can be used for strings, numbers, or mixed data types in lists.
5 Uses Zero-Based Indexing The first element in the list has an index of 0.
In [ ]:
# Finding the index of an element
topics = ["intensity", "coding", "python", "tutorial"]
index_value = topics.index("python")
print(index_value)
# Output: 2
2

7. insert()¶

Point Description
Use Case The insert() method inserts an element at a specified position in the list. It shifts existing elements to the right without replacing any values.
Syntax list.insert(pos, elmnt)
Parameter pos (Required) — The index position where the element should be inserted.
elmnt (Required) — The value to be inserted. Can be of any data type (string, number, object, etc.).

Useful Information¶

No. Point Description
1 Inserts Without Replacing Existing elements are shifted, not removed.
2 Allows Any Data Type You can insert strings, numbers, objects, or lists.
3 Zero-Based Indexing Index 0 means inserting at the beginning, -1 means before the last element.
4 Works on Empty Lists If the list is empty, the inserted element becomes the first item.
5 Affects List Length The list grows by one element after each insertion.
In [ ]:
# Creating a list of topics
topics = ["intensity", "coding", "tutorial"]

# Inserting 'python' at index 1
topics.insert(1, "python")

print(topics)  # Output: ['intensity', 'python', 'coding', 'tutorial']
['intensity', 'python', 'coding', 'tutorial']

8. pop()¶

Point Description
Use Case The pop() method removes an element at a specified index and returns the removed value. If no index is provided, it removes the last element by default.
Syntax list.pop(pos)
Parameter pos (Optional) — The index of the element to remove. Defaults to -1, which removes the last item.

Useful Information¶

No. Point Description
1 Returns the Removed Value Unlike remove(), pop() returns the deleted element.
2 Default is the Last Element If no index is given, it removes the last item.
3 Uses Zero-Based Indexing The first item is at index 0.
4 Index Must Be Valid Attempting to pop from an empty list or an out-of-range index raises an IndexError.
5 Mutates the Original List The method modifies the list in place.
In [ ]:
# Creating a list of topics
topics = ["intensity", "python", "coding", "tutorial"]

# Removing the element at index 1
removed_item = topics.pop(1)

print(topics)       # Output: ['intensity', 'coding', 'tutorial']
print(removed_item) # Output: 'python'
['intensity', 'coding', 'tutorial']
python

9. remove()¶

Point Description
Use Case The remove() method removes the first occurrence of a specified element from a list.
Syntax list.remove(elmnt)
Parameter elmnt (Required) — The element to be removed. Must exist in the list, or an error is raised.

Useful Information¶

No. Point Description
1 Removes Only the First Occurrence If there are multiple occurrences, only the first one is deleted.
2 Modifies the Original List The method directly changes the list.
3 Raises an Error if Element is Missing If the value is not found, ValueError is raised.
4 Does Not Return a Value The method removes an element but does not return it.
5 Works with Strings, Numbers, and Other Objects The element can be any valid list item type.
In [ ]:
# Creating a list of programming terms
topics = ["intensity", "coding", "python", "coding", "tutorial"]

# Removing the first occurrence of "coding"
topics.remove("coding")

print(topics)  # Output: ['intensity', 'python', 'coding', 'tutorial']
['intensity', 'python', 'coding', 'tutorial']

10. reverse()¶

Point Description
Use Case The reverse() method reverses the order of elements in a list.
Syntax list.reverse()
Parameter No parameters.

Useful Information¶

No. Point Description
1 Modifies the Original List The method alters the existing list instead of creating a new one.
2 Works on Any Data Type Can be used with lists containing strings, numbers, or objects.
3 Does Not Sort the List It only reverses the order of elements, without changing their relative values.
4 Does Not Return a Value The method modifies the list in place and returns None.
5 Useful for Reversing Sequences Often used for reversing order in sorting, stacks, or recent history lists.
In [ ]:
# List of programming terms
topics = ["intensity", "coding", "python", "tutorial"]

# Reversing the list
topics.reverse()

print(topics)  # Output: ['tutorial', 'python', 'coding', 'intensity']
['tutorial', 'python', 'coding', 'intensity']

11. sort()¶

Point Description
Use Case The sort() method sorts the elements of a list in ascending order by default.
Syntax list.sort(reverse=True\|False, key=myFunc)
Parameter reverse (Optional) — If True, sorts in descending order(default is False).
key (Optional) — A function specifying sorting criteria.

Useful Information¶

No. Point Description
1 Modifies the Original List The method changes the list instead of returning a new one.
2 Default Sorting Order By default, sorting is done in ascending order.
3 Can Sort by Custom Criteria The key parameter allows custom sorting logic.
4 Supports Reverse Sorting Setting reverse=True sorts the list in descending order.
5 Works with Strings, Numbers, and Objects Can sort lists of different data types, including dictionaries.
In [ ]:
# List of programming terms
topics = ["intensity", "coding", "python", "tutorial"]

# Sorting in ascending order (default)
topics.sort()
print(topics)  # Output: ['coding', 'intensity', 'python', 'tutorial']

# Sorting in reverse order
topics.sort(reverse=True)
print(topics)  # Output: ['tutorial', 'python', 'intensity', 'coding']

# Function to sort by length of string
def sort_by_length(word):
    return len(word)

# Sorting by length
topics.sort(key=sort_by_length)
print(topics)  # Output: ['python', 'coding', 'tutorial', 'intensity']
['coding', 'intensity', 'python', 'tutorial']
['tutorial', 'python', 'intensity', 'coding']
['python', 'coding', 'tutorial', 'intensity']

Sorting a List of Dictionaries by a Key¶

In [ ]:
# List of programming courses with difficulty level
courses = [
    {"course": "Python", "difficulty": 3},
    {"course": "Machine Learning", "difficulty": 5},
    {"course": "Web Development", "difficulty": 2},
    {"course": "Data Science", "difficulty": 4}
]

# Function to sort by difficulty level
def sort_by_difficulty(course):
    return course["difficulty"]

# Sorting by difficulty
courses.sort(key=sort_by_difficulty)

print(courses)
# Output:
# [{'course': 'Web Development', 'difficulty': 2},
#  {'course': 'Python', 'difficulty': 3},
#  {'course': 'Data Science', 'difficulty': 4},
#  {'course': 'Machine Learning', 'difficulty': 5}]
[{'course': 'Web Development', 'difficulty': 2}, {'course': 'Python', 'difficulty': 3}, {'course': 'Data Science', 'difficulty': 4}, {'course': 'Machine Learning', 'difficulty': 5}]
Category
Python Natural Language Processing Generative AI
Tag's
Python Natural Language Processing

Quick Links

  • Home
  • Tutorials
  • About Us
  • Contact Us

Tutorials

  • Python
  • Natural Language Processing
  • Generative AI

Tags

  • Python
  • Natural Language Processing

About Intensity Coding

  • Intensity Coding is your learning hub for Data Science, Machine Learning, Deep Learning, NLP, and Generative AI. From beginner to expert level, we offer clear tutorials, real-world examples, and up-to-date insights. Our content simplifies complex topics to help you grow in your AI journey.
Intensity Coding

© 2025 Intensity Coding. All Rights Reserved.

Privacy Policy Terms and Conditions Disclaimer