Python List: Beyond the Basics

Dive deeper into Python list, mastering techniques like sorting, filtering, and transforming data. Optimize your code and unlock the full potential of lists in your Python projects.

Python-List
Table of Contents

Begin your Python list journey with this quick 7-minute read covering fundamentals. It’s the perfect foundation before exploring the advanced techniques discussed in this article. Python Lists: Basics covers the essentials of creating, accessing, and modifying lists. Learn how to add, remove, and search for elements, setting a strong foundation for further list manipulation.


How to Create a List in Python

You can create a list using different methods, offering flexibility for various situations.

From String to List in Python

You can create a list directly from a string, splitting the string’s contents into individual elements. This is a convenient way to work with text data as a list. Here’s how it works:

Example

sentence = "This is a sample sentence."
words = sentence.split()
print(words)

Explanation

  • Line 1: Creates a string variable sentence.
  • Line 2: Splits the sentence using the .split() method and assigns the resulting list of words (split at whitespace by default) to the variable words.
  • Line 3: Prints the contents of the words list, showing each word from the sentence as a separate item.

Output

[‘This’, ‘is’, ‘a’, ‘sample’, ‘sentence.’]


Generating List Using range()

Python’s range() function helps generate sequences of numbers. You can convert this sequence into a list using the list() constructor. This is useful when you need an ordered list of numbers within a specific range.

Example

even_numbers = list(range(2, 11, 2))
print(even_numbers)

Code Explanation

  • Line 1: Uses list() with range(). range(2, 11, 2) generates numbers starting from 2 (inclusive) up to but not including 11, with a step of 2 (ensuring even numbers). The result is converted to a list and assigned to even_numbers.
  • Line 2: Prints the contents of the even_numbers list.

Output

[2, 4, 6, 8, 10]


Extracting List from Dictionary

You can create a list directly from the keys or values of a dictionary. This is handy when working with those elements as a separate list. Here’s how it works:

Example of Creating List from Keys and Values

my_dictionary = {"name": "Alice", "age": 30, "city": "New York"}
name_list = list(my_dictionary.keys())
age_list = list(my_dictionary.values())
print(name_list)
print(age_list)

Code Explanation

  • Lines 1-2: Create a dictionary my_dictionary with key-value pairs. Then, create a list name_list using list() and the .keys() method to get a list of the dictionary’s keys.
  • Line 3: Creates another list age_list using list() and the .values() method to get a list of the dictionary’s values.
  • Lines 4-5: Print the contents of both lists. name_list will show the keys (“name“, “age“, “city“), and age_list will show the values (“Alice“, 30, “New York“).

Output

[‘name’, ‘age’, ‘city’]
[‘Alice’, 30, ‘New York’]


Python List Comprehensions

List comprehensions provide a concise way to create lists in Python, especially when you’re working with transformations or filtering on existing iterables. Here’s the basic structure:

Syntax

new_list = [expression for item in iterable if condition]

  • new_list: This stores the resulting list you’re creating.
  • [ ]: Square brackets define the list structure.
  • expression: This is an operation applied to each item in the iterable.
  • for item in iterable: This iterates through each item in the sequence (like a list, string, or range).
  • if condition (optional): This adds a filtering step to include only elements meeting the condition.

Example

squared_numbers = [num * num for num in range(1, 6)]
print(squared_numbers)

Code Explanation

  • Line 1: Uses list comprehension. The expression num * num squares each number (num) from the range(1, 6) sequence. This creates a list named squared_numbers.
  • Line 2: Prints the contents of squared_numbers, showing the squares of numbers from 1 to 5.

Output

[1, 4, 9, 16, 25]


Adding Elements to Python List

Python list is flexible and allows you to add elements after creation. Here are the common methods for adding items:

The += Operator for List Addition

While the += operator is commonly used for adding numbers in Python, it can also be beneficial for adding elements to a list. Here’s how it works:

Example

fruits = ["apple", "banana"]
fruits += ["cherry", "mango"]
print(fruits)

Note: Unlike append, which adds a single element, += adds each element from the iterable to the end of the original list.

Code Explanation

  • Line 1: Creates a list fruits with two elements.
  • Line 2: Uses the += operator to add the elements from the list ["cherry", "mango"] to the end of fruits. Unlike append which adds one element at a time, here += adds each element from the iterable.
  • Line 3: Prints the modified fruits list, showing all the elements added using the += operator.

Output

[‘apple’, ‘banana’, ‘cherry’, ‘mango’]


Extending Python List with extend()

Python’s list allows you to extend their content after creation. The .extend() method is useful when adding multiple elements at once.

Example

vegetables = ["carrot", "cucumber"]
more_vegetables = ["broccoli", "spinach"]
vegetables.extend(more_vegetables)
print(vegetables)

Note: Unlike append, which adds a single element, .extend() iterates through the entire iterable and adds each element to the end of the original list.

Code Explanation

  • Lines 1-2: Create two lists: vegetables with “carrot” and “cucumber”, and more_vegetables with “broccoli” and “spinach”.
  • Line 3: Uses the .extend() method on vegetables. We provide the more_vegetables list as the argument. .extend() iterates through more_vegetables and adds each element (“broccoli” and “spinach”) to the end of vegetables.
  • Line 4: Print the contents of the modified vegetables list, showing all the elements after using .extend().

Output

[‘carrot’, ‘cucumber’, ‘broccoli’, ‘spinach’]


Precise Insertion with insert()

You can insert elements at specific positions within a list. The .insert() method provides this functionality, allowing you to modify the order of elements or add items at desired locations.

Syntax

list_name.insert(index, element)

  • list_name: The name of the list you want to modify.
  • .insert(index, element):
    • .insert(): This method inserts an element into the list.
    • index: This specifies the index at which you want to insert the element. Remember, Python indexing starts from 0, so the first element has index 0.
    • element: This is the element you want to insert at the specified index.

Example

weekdays = ["Monday", "Wednesday", "Friday"]
weekdays.insert(1, "Tuesday")
print(weekdays)

Code Explanation

  • Line 1: Creates a list weekdays with three weekdays.
  • Line 2: Uses .insert() on weekdays. We provide the index 1 (between Monday and Wednesday) and the element “Tuesday” to insert. The original list is modified by inserting “Tuesday” at the specified index.
  • Line 3: Prints the contents of the updated weekdays list, showing “Tuesday” inserted at index 1.

Output

[‘Monday’, ‘Tuesday’, ‘Wednesday’, ‘Friday’]


How to Access Python List Elements

Here are the common methods for accessing list elements:

Negative Indexing in Python List

Negative indexing provides an alternative way to access elements in a Python list. It allows you to start counting from the end of the list instead of the beginning.

Syntax

list_name[-index]

  • [-index]: Square brackets enclosing the negative index.
    • : The minus sign indicates negative indexing.
    • index: This represents the position relative to the end of the list. For example, -1 refers to the last element, -2 refers to the second-last element, and so on.

Example

colors = ["red", "green", "blue", "yellow"]
last_color = colors[-1]
second_last_color = colors[-2]
print(last_color)  # Output: yellow
print(second_last_color)

Code Explanation

  • Line 1: Creates a list colors with four color names.
  • Lines 2-3: Access elements using negative indexing. colors[-1] retrieves the element at index -1 (which is the last element, “yellow”). Similarly, colors[-2] retrieves the element at index -2 (which is the second-last element, “blue”).
  • Lines 4-5: Print the values of last_color and second_last_color, demonstrating how negative indexing works to access elements from the end of the list.

Output

blue


Extracting List Slices

Python list offers a powerful feature called slicing, which allows you to extract a sublist containing a specific portion of elements. Here’s how slicing works:

Syntax

 sub_list = list_name[start:stop:step] (assuming a step value is included)

  • sub_list: This stores the resulting sublist you extract.
  • list_name: The name of the original list you’re working with.
  • [start:stop:step]: Square brackets define the slicing operation.
    • start (optional): This index specifies where the slice begins (inclusive). Defaults to 0 (the first element).
    • stop (required): This index specifies where the slice ends (exclusive). The element at this index is not included in the sublist.
    • step (optional): This value determines the step size when iterating through the list for the slice. Defaults to 1 (including every element).

Example

numbers = [1, 2, 3, 4, 5, 6, 7]
sublist1 = numbers[2:5]
sublist2 = numbers[::2]
print(sublist1)
print(sublist2)

Code Explanation

  • Line 1: Creates a list numbers containing integers.
  • Line 2: Creates a sublist sublist1 using slicing. numbers[2:5] extracts elements starting from index 2 (inclusive, which is 3) up to but not including index 5, resulting in [3, 4, 5].
  • Line 3: Creates another sublist sublist2. Here, numbers[::2] extracts every other element by specifying a step size of 2, resulting in [1, 3, 5, 7].
  • Lines 4-5: Print the contents of both sublists, demonstrating how slicing allows you to create sublists from the original list.

Output

[3, 4, 5]
[1, 3, 5, 7]


Finding Elements Within Python List

Python provides multiple ways to find elements in a list. Here’s a breakdown of some common methods, along with their use cases:

in/not in for Membership Tests

The most straightforward way to check if an element exists in a Python list is by using the in and not in operators. These operators provide a quick way to determine element presence without complex loops or functions.

Syntax

element in list_name

Checks if element exists in list_name (returns True/False)

element not in list_name

Checks if an element does not exist in list_name (returns True/False)

Example

fruits = ["apple", "banana", "orange"]
if "cherry" in fruits:
    print("cherry is present")
else:
    print("cherry is not present")
if "apple" not in fruits:
    print("apple is not present")
else:
    print("apple is present")

Code Explanation

  • Lines 1-2: Create a list fruits and use an if statement with the in operator. If “cherry” is found in fruits, it prints “cherry is present”. Otherwise, it prints “cherry is not present”.
  • Lines 6-8: Another if statement with the not in operator. Here, we check the opposite condition. Since “apple” exists in fruits, the else block executes, printing “apple is present”.

Output

cherry is not present
apple is present


Counting with count()

Counting element occurrences is a frequent task when working with Python lists. The .count() method is handy for this purpose. It efficiently iterates through the list and returns the number of times a specific element appears.

Syntax

list_name.count(element)

.count(element): The .count() method counts the occurrences of the specified element within the list.

Example

vegetables = ["carrot", "cucumber", "carrot", "broccoli"]
carrot_count = vegetables.count("carrot")
print(carrot_count)  # Output: 2 (appears twice in the list)

Code Explanation

  • Line 1: Creates a list vegetables with some vegetables.
  • Line 2: Uses the .count() method on vegetables. We provide “carrot” as the argument. .count() searches for “carrot” within vegetables and returns the number of times it appears (which is 2 in this case).
  • Line 3: Prints the result stored in carrot_count, showing there are two “carrot” elements.

Using any() to Check Existence

The any() function in Python is used to check conditions within iterables like lists. When searching elements in a list, you can use any() to determine if at least one element meets specific criteria.

Syntax

any(iterable)

  • any(): The any() function itself.
  • iterable: This can be a list, a string (interpreted as a sequence of characters), or any sequence-like object containing the elements you want to evaluate.

Note: any() returns True if at least one element in the iterable evaluates to True (considering non-zero numbers, non-empty strings, and True booleans as True). It returns False if all elements evaluate to False (including 0, empty strings, and False booleans).

Example

numbers = [1, 2, 0, -5]
has_positives = any(num > 0 for num in numbers)
print(has_positives)  # Output: True (since 1 and 2 are positive)

Explanation

  • Line 1: Creates a list numbers with various integers.
  • Line 2: Uses any() with a generator expression. The expression num > 0 checks if each num in numbers is greater than 0. any() evaluates if at least one element satisfies this condition (i.e., if any number is positive).
  • Line 3: Prints the result stored in has_positives. Since there are positive numbers (1 and 2), any() returns True.

Removing Elements from Python List

Python offers multiple ways to remove elements from a list, giving flexibility for different scenarios. Here’s a breakdown of the most common methods:

Targeted Deletion with del

The del keyword in Python allows you to delete elements from a list. It allows you to target specific elements by their index or remove a slice of elements at once.

Deleting by index Syntax

del list_name[index]

  • del: The del keyword.
  • [index]: Square brackets enclosing the element’s index you want to delete.

Deleting a slice Syntax

del list_name[start:stop:step] 

Note: Remember that Python uses zero-based indexing, so the first element has an index of 0. Using del permanently removes elements and cannot be undone.

Example

letters = ['a', 'b', 'c', 'd', 'e']
del letters[2]
del letters[1:3]
print(letters)

Code Explanation

  • Lines 1-2: Create a list letters with some letters. Then, del letters[2] deletes the element at index 2, which is ‘c’ in this case.
  • Line 3: del letters[1:3] removes a slice of elements. Slicing starts at index 1 (inclusive, which is ‘b’) and goes up to but not including index 3, effectively removing ‘b’, ‘c’, and ‘d’.
  • Line 4: Prints the modified letters list, showing only ‘a’ and ‘e’ remaining after the deletions.

Output

[‘a’, ‘e’]


Popping Elements with pop()

The .pop() method is used to remove elements from a list. It not only removes an element but also returns its value. Here’s how it works:

Syntax

element = list_name.pop(index) (optional index)

  • list_name: The name of the list you want to modify.
  • .pop(index):
    • .pop(): This method removes and returns an element from the list.
    • index (optional): This specifies the index of the element you want to remove. By default (if no index is provided), .pop() removes and returns the last element in the list.

Example

colors = ["red", "green", "blue", "yellow"]
removed_color = colors.pop()
print(removed_color) # Output: yellow
first_color = colors.pop(0)
print(colors)

Code Explanation

  • Lines 1-2: Create a list colors and use .pop() without an index. By default, .pop() removes and returns the last element, “yellow” in this case, and stores it in removed_color.
  • Lines 3-4: We explicitly provide an index 0 to .pop(). This removes and returns the element at index 0 (“red”), storing it in first_color.
  • Line 5: Prints the updated colors list, showing “red” (initially at index 0) is gone.

Output

[‘green’, ‘blue’]


Clearing a List with clear()

Removes all elements inside the list, leaving you with an empty list.

Example

shopping_list = ["bread", "milk", "eggs", "cheese"]
shopping_list.clear()
print(shopping_list)  # Output: [] (empty list)

Note: Using .clear() entirely empties the list. If you want to preserve the list and modify a copy, consider creating a copy using slicing or the copy.copy() function before using .clear().

Explanation

  • Line 1: Creates a list shopping_list containing some shopping items.
  • Line 2: Uses .clear() on shopping_list. This method efficiently removes all elements from the list, essentially making it empty.
  • Line 3: Prints the modified shopping_list, showing empty after using .clear().

Slice-Based Deletion

Python list allows you to delete various elements simultaneously using a clever technique. You can assign an empty list [ ] to a slice of the original list. Here’s how it works:

Syntax

list_name[start:stop] = []

= [ ]: Assigning an empty list [ ] to the slice removes the elements within that range.

Note: Slicing uses zero-based indexing, so be mindful of the indices when specifying the range for deletion.

Example

numbers = [1, 2, 3, 4, 5, 6, 7]
numbers[2:5] = []
print(numbers)  # Output: [1, 2, 6, 7] (elements at indices 2, 3, and 4 are removed)

Code Explanation

  • Line 1: Creates a list numbers containing integers.
  • Line 2: Uses slicing with an assignment. numbers[2:5] = [] removes elements from index 2 (inclusive, which is 3) up to but not including index 5. Assigning an empty list [] to this slice effectively deletes those elements.
  • Line 3: Prints the modified numbers list, demonstrating how slicing with an empty list assignment can remove a range of elements.

Merging Lists: Python List Concatenation

Combining multiple lists into a single list is a frequent operation in Python. This process is called concatenation. Here’s how you can achieve this:

Example

colors1 = ["red", "green"]
colors2 = ["blue", "yellow"]
all_colors = colors1 + colors2  # Concatenate colors1 and colors2
print(all_colors)

Code Explanation

  • Lines 1-2: Create two lists, colors1 and colors2, containing some color names.
  • Line 3: Uses the + operator for concatenation. all_colors = colors1 + colors2 combines colors1 and colors2 into a new list named all_colors. The elements from colors2 are appended to the end of colors1.
  • Line 4: Prints the all_colors list, demonstrating the combined elements from both original lists.

Output

[‘red’, ‘green’, ‘blue’, ‘yellow’]


Repeating List in Python

You can easily create a new list that repeats the elements of an existing list a specific number of times. This repetition is achieved using the multiplication operator (*).

Syntax

repeated_list = list_name * number

* number: The multiplication operator (*) creates copies of the list and combines them. The number specifies how many times to repeat the original list.

Note: The multiplication operator creates a shallow copy of the list during repetition. If the list contains mutable elements (like lists or dictionaries), changes to those elements within the repeated copies will affect all repetitions.

Example

letters = ['a', 'b']
repeated_letters = letters * 3
print(repeated_letters)

Code Explanation

  • Line 1: Creates a list letters containing two letters.
  • Line 2: Uses the multiplication operator for repetition. repeated_letters = letters * 3 creates a new list repeated_letters by repeating the elements in letters three times.
  • Line 3: Prints the repeated_letters list, showing the repeated elements from the original list.

Output

[‘a’, ‘b’, ‘a’, ‘b’, ‘a’, ‘b’]


Essential List Functions in Python

Python provides a rich set of built-in functions that work seamlessly with lists. These functions offer powerful tools for analyzing and manipulating list data. Here’s an overview of some common ones:

Finding List Length with len()

This function returns the total number of items (length) of a list.

len(list_name)

max() with List

This function finds the element with the largest value in the list. Lists must contain comparable elements such as numbers or strings.

max(list_name)

min() with List

This function finds the element with the smallest value in the list (similar to max()). Lists must contain comparable elements.

min(list_name)

Example

numbers = [5, 2, 8, 1, 9]  
list_length = len(numbers)  
largest_number = max(numbers)  
smallest_number = min(numbers)  
print("Length of the list:", list_length)  
print("Largest number:", largest_number)  
print("Smallest number:", smallest_number)

Code Explanation

  • Line 1: Creates a list numbers containing integers.
  • Lines 2-4: These lines demonstrate using the built-in functions:
    • len(numbers) calculates the list length and stores it in list_length.
    • max(numbers) finds the maximum value in numbers and stores it in largest_number.
    • min(numbers) finds the minimum value in numbers and stores it in smallest_number.
  • Lines 5-7: Print the calculated results.

Output

Length of the list: 5
Largest number: 9
Smallest number: 1


Copying Python List Correctly

Creating a copy of a list is a common task when you want to work with a modified version without affecting the original list. Python’s list methods provide a convenient way to achieve this using the .copy() method.

Example

fruits = ["apple", "banana", "orange"]
fruits_copy = fruits.copy()
fruits_copy.append("mango")
print(fruits)  # Output: ['apple', 'banana', 'orange']
print(fruits_copy)  # Output: ['apple', 'banana', 'orange', 'mango'] (copy is modified)

Note: The .copy() method creates a shallow copy. This means changes to top-level elements of the copy will be reflected in the original list if those elements are mutable (like lists or dictionaries within the lists).

Code Explanation

  • Lines 1-2: Create a list fruits and use .copy() to create a copy named fruits_copy.
  • Line 3: Add “mango” to fruits_copy (the copy). Since it’s a shallow copy, changes to top-level elements in the copy are reflected.
  • Lines 4-5: Print both lists separately. The original fruits list remains unchanged, while fruits_copy (the copy) shows the added “mango”.

List Comparisons in Python

Comparing lists in Python is essential for various tasks like checking content equality or identifying differences. Here’s a look at two common approaches:

List Order Matters (Element-Wise Comparison)

This checks if both lists have the same elements in the same order.

list1 == list2

List Order Doesn’t Matter (Considering Set Membership)

This converts both lists to sets using set(). Sets don’t maintain order, so this approach checks if both lists contain the same elements regardless of their order.

set(list1) == set(list2)

Note: The first approach (==) is generally faster for simple comparisons when order matters. The second approach (set()) is useful when order is irrelevant, and you only care about matching elements.

Example

list1 = ["apple", "banana", "cherry"]
list2 = ["banana", "apple", "cherry"]
list3 = ["apple", "banana", "mango"]

# Check if elements are equal in the same order (order matters)
if list1 == list2:
    print("list1 and list2 are equal (same order)")
else:
    print("list1 and list2 are not equal (different order)")

# Check if elements are equal regardless of order (order doesn't matter)
if set(list1) == set(list2):
    print("list1 and list2 have the same elements (regardless of order)")
else:
    print("list1 and list2 don't have the same elements (regardless of order)")

# Compare with a different list (different elements)
if set(list1) == set(list3):
    print("list1 and list3 have the same elements (regardless of order)")
else:
    print("list1 and list3 don't have the same elements (regardless of order)")

Code Explanation

  • Lines 1-3: Create three lists, list1, list2, and list3 for comparison.
  • Lines 6-9: Check if list1 and list2 are equal using ==. They have the same elements but in a different order, so this will print “not equal”.
  • Lines 12-15: Converts both to sets using set() and checks for equality using set() == set(). Since they have the same elements (irrespective of order), this will print “have the same elements”.
  • Lines 18-21: Similarly, it compares list1 and list3 using sets. Since they have different elements, this will print “don’t have the same elements” regardless of the order check.

Output

list1 and list2 are not equal (different order)
list1 and list2 have the same elements (regardless of order)
list1 and list3 don’t have the same elements (regardless of order)


Reversing List: reversed() vs. reverse()

Reversing a list in Python is a common task, and you have two main methods to accomplish it:

reversed() with List

This function creates a reverse iterator over the list. The list() constructor converts it back into a new reversed list.

Note: It doesn’t modify the original list.

new_list = list(reversed(list_name))

reverse() with List

This method directly reverses the list in place, affecting the original list.

list_name.reverse()

Example

colors = ["red", "green", "blue"] 

# Using reversed() - creates a copy 
reversed_colors_copy = list(reversed(colors))  
print("Original:", colors)  # Output: ['red', 'green', 'blue']
print("Reversed copy:", reversed_colors_copy)  # Output: ['blue', 'green', 'red']

# Using .reverse() - modifies original list
colors.reverse()  
print("Original after reversing:", colors)

Code Explanation

  • Line 1: Creates a list colors.
  • Lines 4-6: The reversed() function creates a reversed iterator. Converting it to a list using list() provides a reversed copy in reversed_colors_copy. The original colors remains unchanged.
  • Lines 9-10: The .reverse() method directly modifies the original list. Therefore, subsequent access of colors will show the reversed order.

Output

[‘blue’, ‘green’, ‘red’]


Sorting List in Python

Sorting lists is essential for organizing and analyzing data in Python. Here’s a breakdown of two common approaches:

sorted() for Flexibility

The sorted() function creates a new sorted list and preserves the original list.

new_sorted_list = sorted(list_name)

In-Place Sorting with .sort()

list_name.sort()

This method directly sorts the original list in place, modifying its order.

Example

numbers = [5, 1, 3, 8, 2]

# Using sorted() - creates a copy 
sorted_numbers_copy = sorted(numbers)  
print("Original:", numbers)  # Output: [5, 1, 3, 8, 2]
print("Sorted copy:", sorted_numbers_copy)  # Output: [1, 2, 3, 5, 8]

# Using .sort() - modifies original list
numbers.sort()  
print("Original after sorting:", numbers)  # Output: [1, 2, 3, 5, 8]

Code Explanation

  • Line 1: Creates a list numbers containing unsorted numbers.
  • Lines 4-6: The sorted() function creates a new sorted list and stores it in sorted_numbers_copy. The original numbers remains unchanged.
  • Lines 9-10: The .sort() method sorts the original numbers list directly. It modifies the list in place, changing its order permanently.

Working with Nested Lists in Python

Nested lists allow you to create a list that contains other lists as its elements. Imagine nested lists like a series of boxes within boxes. Each outer list represents a larger container, and the inner lists are items neatly organized within those containers.

Accessing Elements within Nested Lists

Accessing elements within nested lists requires specifying a series of indexes, like navigating a maze. Here’s how it works:

Syntax

element = nested_list[outer_index][inner_index]

  • nested_list: The name of your nested list.
  • [outer_index]: The first index accesses the desired inner list within the main (outer) list.
  • [inner_index]: The second index selects the element within the chosen inner list.

Example

grocery_list = [  # Create a nested list
    ["apples", "bananas", "pears"],  # Sublist 0 (fruits)
    ["milk", "cheese", "eggs"],     # Sublist 1 (dairy)
    ["bread", "cereal", "pasta"]     # Sublist 2 (grains)
]

first_fruit = grocery_list[0][0]  # Access the first element (apples) in sublist 0
second_dairy = grocery_list[1][1]  # Access the second element (cheese) in sublist 1
last_grain = grocery_list[2][2]  # Access the last element (pasta) in sublist 2

print(first_fruit)  # Output: apples
print(second_dairy)  # Output: cheese
print(last_grain)  # Output: pasta

Code Explanation

  • Lines 1-5: Create a nested list grocery_list representing grocery categories (outer list) with items within each category (inner lists).
  • Lines 7-9: Access elements using double indexing.
    • grocery_list[0][0] refers to the first index (sublist 0 or fruits) and then the first index within that sublist (apples).
    • Similar logic applies to grocery_list[1][1] (cheese) and grocery_list[2][2] (pasta).
  • Lines 11-13: Print the accessed elements from each sublist.

Adding Elements within Nested Lists

Adding elements to nested lists allows you to expand your data structure. Here’s how you can achieve this:

insert() Method

The .insert() method inserts a new element into a list at a specified position, shifting existing elements to the right to make space.

Syntax

nested_list[outer_index].insert(inner_index, element)

  • inner_index: Position within the inner list where you want to insert the element.
  • element: The new element to be inserted at the specified position.

append() Method

The .append() method adds a single element to the end of an existing list.

nested_list[outer_index].append(element) 

Example

matrix = [[1, 2], [3, 4]]  

# Inserting using insert()
matrix[0].insert(1, 2.5)

# Appending using append()
matrix[1].append(5)  # Append 5 to the end of the second inner list

print(matrix)

Code Explanation

  • Line 1: Creates a nested list matrix.
  • Lines 4: Uses .insert() to add ‘2.5‘ at index 1 of the first inner list.
  • Lines 7: Employs .append() to add ‘5‘ to the end of the second inner list.
  • Line 9: Prints the modified matrix.

Output

[[1, 2.5, 2], [3, 4, 5]]


Modifying Elements within Nested Lists

Modifying elements within nested lists allows you to change existing data. Here’s how to update elements using their index positions:

Syntax

nested_list[outer_index][inner_index] = new_value

The assignment operator (=) replaces the element at the specified indices with the new_value.

Example

colors = [  # Create a nested list
    ["red", "green", "blue"],  # Sublist 0
    ["yellow", "orange", "purple"]  # Sublist 1
]

colors[0][1] = "lime"
colors[1][0] = "gold"

print(colors)

Code Explanation

  • Lines 1-4: Create a nested list colors with sublists for primary and secondary colors.
  • Lines 6-7: Update elements using their index positions.
    • colors[0][1] = "lime" replaces “green” with “lime” at index 1 of sublist 0.
    • colors[1][0] = "gold" replaces “yellow” with “gold” at index 0 of sublist 1.
  • Line 9: Print the modified colors list, demonstrating the updated elements.

Output

[[‘red’, ‘lime’, ‘blue’], [‘gold’, ‘orange’, ‘purple’]]


Nested List Iteration

Traversing nested lists element by element is often necessary for processing or analyzing the data they hold. Nested for loops provides a way to achieve this.

Syntax

for outer_element in nested_list:  # Loop through outer list elements
    for inner_element in outer_element:  # Loop through inner list elements
        # Your code to process each element (outer_element, inner_element)

Example

grocery_list = [
    ("Fruits", ["apples", "bananas"]),
    ("Dairy", ["milk", "cheese", "eggs"]),
    ("Grains", ["bread", "pasta"])
]

# Loop through each category and its items
for category, items in grocery_list:
    print(f"--- {category} ---")  # Print category header
    for item in items:  # Loop through inner list (items)
        print(item)  # Print each item

Code Explanation

  • Lines 1-8: Create a nested list grocery_list with categories (outer list) and items within each category (inner lists). The outer loop iterates through each category, and the inner loop iterates through the items within that category.

Output

— Fruits —
apples
bananas
— Dairy —
milk
cheese
eggs
— Grains —
bread
pasta


How to Remove Duplicates from Python List

Eliminating duplicate items from a list is a frequent task in Python. Here are two common approaches to achieve this:

Using a set

Sets inherently don’t allow duplicates. Converting a list to a set and back to a list removes duplicates.

Syntax

unique_list = list(set(original_list))

  • set(original_list) creates a set from the original_list, eliminating duplicates.
  • list() converts the set back to a list (optional, for compatibility).

Using a Loop (For Loop With Conditional Statement)

This method iterates through the list, checking if an element exists before adding it to a new list.

Syntax

unique_list = []
for item in original_list:
    if item not in unique_list:
        unique_list.append(item)

Example

numbers = [1, 2, 2, 3, 4, 4, 5]

# Using set
unique_numbers_set = list(set(numbers))
print("Unique using set:", unique_numbers_set)  # Output: Unique using set: [1, 2, 3, 4, 5]

# Using loop
unique_numbers_loop = []
for number in numbers:
    if number not in unique_numbers_loop:
        unique_numbers_loop.append(number)
print("Unique using loop:", unique_numbers_loop)  # Output: Unique using loop: [1, 2, 3, 4, 5]

Code Explanation

  • Lines 1-5: Create a list numbers with duplicates. The set() method eliminates duplicates and converts the result to a list using list().
  • Lines 8-12: The loop iterates through numbers. If an element isn’t found in unique_numbers_loop (initialized empty), it’s appended using .append(). This builds a new list without duplicates.

Multidimensional List in Python

In Python, you can create lists that contain other lists, essentially building a multidimensional structure. This allows you to represent complex data with rows and columns (like a matrix) or hierarchical relationships.

Syntax

multidimensional_list = [[element11, element12, ...],  # Row 1 (inner list)
                        [element21, element22, ...],  # Row 2 (inner list)
                        ...]                             # More rows (inner lists)

Example (Creating a 2D List Representing a Tic-Tac-Toe Board)

tic_tac_toe = [  # Outer list representing the board
    [" ", " ", " "],  # Row 1 (inner list)
    [" ", " ", " "],  # Row 2 (inner list)
    [" ", " ", " "]   # Row 3 (inner list)
]

print(tic_tac_toe)

Code Explanation

  • Lines 1-5: Create a multidimensional list tic_tac_toe. Each inner list represents a row on the tic-tac-toe board, and elements within each inner list represent the cells (initially empty).
  • Line 7: Prints the tic_tac_toe list, showing the initial empty board.

Output

[[‘ ‘, ‘ ‘, ‘ ‘], [‘ ‘, ‘ ‘, ‘ ‘], [‘ ‘, ‘ ‘, ‘ ‘]]