Python Lists
Python Lists

A Python list is a built-in data structure that allows you to store and organize a collection of items in a single variable. The list items are mutable, and they are ordered sequences of elements enclosed in square brackets ([]).

Lists can contain elements of different data types, such as integers, floats, strings, booleans, and even other lists.

It is worth notating that each element in a list has a unique index, starting from 0 for the first element, 1 for the second element, and so on.

Lists are ordered, meaning the order of elements in a list is preserved and can be accessed using their respective indices.

Characteristics of List Items

The key characteristics of Python lists are:

  1. Ordered: The elements in a list are stored in a specific order, and this order is maintained when accessing or modifying the elements. This means list items can be accessed or modified using their index.

    Example:

    
    """
    List items are Ordered and such order is maintained even when accessing or modifying them using their index.
    """
    # Create a list and print its values
    programming = ["Python", "Java", "C++", "Pascal"]
    numbers = [2,44,66,77,8,9,1]
    
    print(programming)
    print(numbers)
    

    Output:

    
    ['Python', 'Java', 'C++', 'Pascal']
    [2, 44, 66, 77, 8, 9, 1]
    
  2. Changeable (Mutable): List items can be modified after the list is created. This means the list items stored in the list variable can be updated, added, or removed an element from a list. Other modifications that can be performed in a list are discussed below section (for example: Change List Items, Add List Items, Remove List Items, etc.).

    Example:

    
    """
    List items are Changeable means items can be modified after the list is created. 
    """
    # Create a list, add new items and print its values
    programming = ["Python", "Java", "C++", "Pascal"]
    numbers = [2,44,66,77,8,9,1]
    
    # Before it has been modified
    print(programming)
    print(numbers)
    
    programming[2] = ["Kotlin"]
    numbers[3] = [100]
    
    # After it has been modified
    print(programming) 
    print(numbers)
    

    Output:

    
    ['Python', 'Java', 'C++', 'Pascal']
    [2, 44, 66, 77, 8, 9, 1]
    
    ['Python', 'Java', ['Kotlin'], 'Pascal']
    [2, 44, 66, [100], 8, 9, 1]
    
  3. Allow Duplicate Values: Lists can contain duplicate values. This means it is possible to have multiple occurrences of the same element in a list.

    Example:

    
    """
    List items aAllow Duplicate Values means it is possible to have multiple occurrences 
    of the same element in a list. 
    """
    # Create a list, add new items and print its values
    programming = ["Python", "Java", "Java", "C++", "Pascal", "C++"]
    numbers = [2,44,66,77,77,9,2,9]
    
    print(programming)
    print(numbers)
    

    Output:

    
    ['Python', 'Java', 'Java', 'C++', 'Pascal', 'C++']
    [2, 44, 66, 77, 77, 9, 2, 9]
    

Data Types in Lists

Python lists have the capability to hold various types of data, including integers, floats, strings, booleans, and even nested lists.

Example:


# Create a list, and add items with diffrent data type and print its values

var_list = [12, 2.5, "Python", True, [3, 4, "Java", False]]

print(var_list)

Output:


[12, 2.5, 'Python', True, [3, 4, 'Java', False]]

In the above example, var_list variable contains an integer, a float, a string, a boolean, and another list as its elements.

Check List Type

In order to check the kind of data type of a list in Python, you can use the type() function.

Example:


# Create a list, and check its data type and print it

var_list = [12, 2.5, "Python", True, [3, 4, "Java", False]]

print(type(var_list))

Output:


<class 'list'>

In the above example, the type() function is used to determine the data type of var_list, which is a list. The output will be <class 'list'>, this shows that var_list is of type list.

Check List Length

In Python we are able to check the length of a list in Python, by using a built-in function called the len().

Example:


# Create a list, and check its lengeth and print it

var_list = [12, 2.5, "Python", True, [3, 4, "Java", False]]

print(var_list)
print(len(var_list))

Output:


[12, 2.5, 'Python', True, [3, 4, 'Java', False]]
5

In the above example, we have shown how to use the len() function in order to retrieve the length of the var_list list. The len() function then returns the number of elements in the list, which in this case is 5. The result is then printed using the print()function.

The list() Constructor

In Python, you can create a list using the list() constructor. This function converts an iterable (such as a string, tuple, or another list) into a new list.

Example:


# Create a list using list constructor in Python
var_str = "This is a string"
var_tuple = ("Python", "Java", "Java", "C++", "Pascal", "C++")

var_list_1 = list(var_str)
var_list_2 = list(var_tuple)


print(var_list_1) 
print(var_list_2)

# Check their type
print(type(var_list_1))
print(type(var_list_2))

Output:


['T', 'h', 'i', 's', ' ', 'i', 's', ' ', 'a', ' ', 's', 't', 'r', 'i', 'n', 'g']
['Python', 'Java', 'Java', 'C++', 'Pascal', 'C++']

<class 'list'>
<class 'list'>

The above code shows the usage of the list constructor function in Python to convert different data types into lists.

The two variables declared var_str contain a string and var_tuple containing a tuple. The list constructor, list(), is used to convert these data types into lists. The list() constructor takes an iterable as an argument and creates a new list with its elements.

Access List Items

After you have been created a list, its time to know how to access list items using different techniques. For example, in Python you can access individual items in a list by using their index. List indexing starts at 0 for the first element, -1 for the last element, and so on.

This means Python has different ways of accessing the list items and some of these are using different ways of slicing or indexing such as positive indexing, negative indexing, positive range indexing, and negative range indexing.

In Python you can access individual items from a list by using square brackets [] and specify the index of the item you want to access inside the brackets.

Positive Indexing

Positive indexing refers to accessing elements in a list using indices that start from 0 and increment by 1.

The first element in a list has an index of 0, the second element has an index of 1, and so on.

Positive indexing allows you to access elements from the beginning of the list.

Example:


# Access list items in Python
programming = ["Python", "Java", "C++", "Pascal"]

# Postive indexing
print(programming[0]) 
print(programming[1]) 
print(programming[2]) 
print(programming[3]) 

Output:


Python
Java
C++
Pascal

The above example shows a positive indexing which is a way to access list items. Fo example, the programming[0] accesses the first element in the programming list. While programming[1] up to programming[3]accesses the second, third and fourth items in the programming list.

Negative Indexing

Negative indexing refers to accessing elements in a list using indices that start from -1 and decrement by 1.

The last element in a list has an index of -1, the second-last element has an index of -2, and so on.

Negative indexing allows you to access elements from the end of the list.

Example:


# Access list items in Python
numbers = [2,44,66,77,8,9,1]

# Negative indexing
print(numbers[-1]) 
print(numbers[-2]) 
print(numbers[-3]) 
print(numbers[-4]) 

Output:


1
9
8
77

The above example shows how to access list items using negative indexing technique. For example the numbers[-1] accesses the last element in the numbers list. While the numbers[-2] up to numbers[-4]accesses the second, third and fourth last element in the numbers list.

Positive Range Indexing

Positive range indexing allows you to access a range of elements from a list by specifying a start index and an end index.

The start index is inclusive, while the end index is exclusive (the element at the end index is not included).

Example:


# Access list items in Python
numbers = [2,44,66,77,8,9,1]

# Positive Range indexing
print(numbers[1:5]) 
print(numbers[0:6]) 

Output:


[44, 66, 77, 8]
[2, 44, 66, 77, 8, 9]

The above example shows how to access list items using positive range indexing technique. For example we have accessed the range values of 1 up to 5 in the numbers[1:5] variable, so that the compiler will return the elements from index 1 to index 4 (excluding index 5) in the numbers list.

Negative Range Indexing

Negative range indexing allows you to access a range of elements from a list using negative indices.

During the negative range indexing, the start index is inclusive, while the end index is exclusive (the element at the end index is not included).

Example:


# Access list items in Python
numbers = [2,44,66,77,8,9,1]

# Negative Range indexing
print(numbers[-5:-1]) 
print(numbers[-6:-2]) 

Output:


[66, 77, 8, 9]
[44, 66, 77, 8]

The above example, we have specified the negative range index from -5 to -1, this means the numbers[-5:-1] accesses elements from the fifth-last index to the second-last index in the numbers list. While the the numbers[-6:-2] accesses elements from the sixth-last index to the third-last index in the numbers list.

More Practice About Python List Slicing

Below are some additional examples that enhance your comprehension of lists and showcase the diverse range of operations you can perform on them, thereby expanding your understanding of this data structure.

Example:


# Access list items in Python
programming = ["Python", "Java", "C++", "Pascal"]
numbers = [2,44,66,77,8,9,1]

# Postive indexing
print("Postive indexing")
print(programming[0]) 
print(programming[1]) 
print(programming[3]) 
print(numbers[len(numbers)-1]) # Return the Last item


# Negative indexing
print("\nNegative indexing")
print(numbers[-1]) 
print(numbers[1-len(numbers)]) # (1-7) = -6

# Range indexing
print("\nRange indexing")
print(numbers[1:5]) 

# Slicing from the start
print("\nSlicing from the start")
print(numbers[:6]) 
print(numbers[0:6]) 
print(numbers[:len(numbers)-1]) 

# Slicing to the end
print("\nSlicing to the end")
print(numbers[6:]) 
print(numbers[3:len(numbers)]) 

# Negative range indexing
print("\nNegative range indexing")
print(numbers[-5:-1]) 
print(numbers[-1:len(numbers)]) 
print(numbers[-4:len(numbers)]) 
print(numbers[:2-len(numbers)]) 

# Other
print("\nCalculated indexing")
print(numbers[int(len(numbers) * 0.5):]) 
print(numbers[int(-len(numbers) * 0.5):]) 

Output:


Postive indexing
Python
Java
Pascal
1

Negative indexing
1
44

Range indexing
[44, 66, 77, 8]

Slicing from the start
[2, 44, 66, 77, 8, 9]
[2, 44, 66, 77, 8, 9]
[2, 44, 66, 77, 8, 9]

Slicing to the end
[1]
[77, 8, 9, 1]

Negative range indexing
[66, 77, 8, 9]
[1]
[77, 8, 9, 1]
[2, 44]

Calculated indexing
[77, 8, 9, 1]
[8, 9, 1]

Note: You can use negative indices to access items from the end of the list. -1 corresponds to the last item, -2 to the second-last item, and so on.

numbers[-1] accesses the last item in the numbers list, which is 1.

Change List Items

In Python, you can change individual items in a list by assigning a new value to the desired index.

Example:


# Change List Item

var_list = [10, 20, 30, 40, 50]

# Changing the third item
var_list[2] = 35
print(var_list)

# Changing the last item
var_list[-1] = 55
print(var_list) 

Output:


[10, 20, 35, 40, 50]
[10, 20, 35, 40, 55]

In the above example, we have a list called var_list with five elements. We can change the value of an item by accessing it through its index and assigning a new value to it.

  • var_list[2] = 35 modifies the item at index 2 and updates it to the value 35.
  • var_list[-1] = 55 modifies the last item in the list, which is accessed using negative indexing, and updates it to the value 55.

After modifying the list items, we print the updated list to verify the changes.

By using assignment, you can change the value of any item in a list, allowing you to update or modify the elements as needed.

Note: there are other ways to change items in a list in Python. Here are a few alternative methods:

Change List Items Using List Slicing

You can use list slicing to change multiple items in a list simultaneously. By specifying a range of indices, you can replace a portion of the list with new values.

Example:


# Change List Item using List Slicing
var_list = [10, 20, 30, 40, 50]

var_list[1:4] = [25, 35, 45]
print(var_list)

Output:


[10, 25, 35, 45, 50]

In the above example, we use list slicing with the range 1:4 to select elements at indices 1, 2, and 3. Then, we assign a new list [25, 35, 45] to replace those elements, effectively changing multiple items in one step.

Change List Items Using List Methods

Python provides various list methods that allow you to modify the list in different ways. Some commonly used methods for changing list items include insert(), append(), and extend().

Example:


# Change List Item using List Methods
var_list = [10, 20, 30, 40, 50]

var_list.insert(2, 25)
print(var_list)

var_list.append(60)
print(var_list)

var_list.extend([70, 80, 90])
print(var_list)

Output:


[10, 20, 25, 30, 40, 50]
[10, 20, 25, 30, 40, 50, 60]
[10, 20, 25, 30, 40, 50, 60, 70, 80, 90]

Note: these methods did not change existing items instead they only introduce new items to the list. Therefore in programming, this action is also called change.

In the above example, we use different list methods to modify the var_list list.

  • insert(2, 25) inserts the value 25 at index 2.
  • append(60) adds the value 60 as the last element of the list.
  • extend([70, 80, 90]) extends the list by appending multiple values at once.

These are just a few examples of different methods and techniques you can use to change items in a list. The choice of method depends on your specific requirements and the modifications you want to make to the list.

Add List Items

Adding items to a list in Python refers to the process of appending or inserting new elements into an existing list. There are several ways to accomplish this. Let’s use the variable var_list to demonstrate different methods of adding items to a list.

Add List Item Using Append Method

The append() method allows you to add an item to the end of a list.

Example:


# Add List Item Using Append List Method
var_list = [1, 2, 3]

var_list.append(4)

print(var_list)

Output:


[1, 2, 3, 4]

In the above example, we start with the list [1, 2, 3]. By using the append() method, we add the value 4 to the end of the list, resulting in [1, 2, 3, 4].

Add List Item Using Insert Method

The insert() method allows you to add an item at a specific position within a list.

Example:


# Add List Item Using Insert Method in Python
var_list = [1, 2, 3]

print(var_list)
var_list.insert(1, 5)

print(var_list)

Output:


[1, 2, 3]
[1, 5, 2, 3]

In the above example, we start with the list [1, 2, 3]. Using the insert() method, we specify the index 1 and insert the value 5 at that position. The resulting list becomes [1, 5, 2, 3].

Add List Item Using Concatenation Operator (+)

You can also add two lists together using the concatenation operator +.

Example:


# Add List Item Using Concatenation Operator (+) in Python
var_list = [1, 2, 3]
new_items = [4, 5]

print(var_list)
print(new_items)

var_list = var_list + new_items
print(var_list)

Output:


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

In this example, we have the list [1, 2, 3] assigned to var_list and the list [4, 5] assigned to new_items. By concatenating var_list with new_items using the + operator, we obtain the combined list [1, 2, 3, 4, 5].

The above-discussed way or methods is a way to provide different ways to add items to a list in Python. The choice of method depends on the specific requirements and the position where you want to add the new items to the list.

Remove List Items

Removing items from a list in Python involves deleting or excluding specific elements from the list. There are various methods to accomplish this and here we discuss some of the most important remove operations in list items using Python.

Remove List Items Using Remove Method

The remove() method allows you to remove the first occurrence of a specific value from a list.

Example:


# Remove List Items Using Remove Method in Python
var_list = [1, 2, 3, 4, 5]

print(var_list)

var_list.remove(3)

print(var_list)

Output:


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

In the above example, we have the list [1, 2, 3, 4, 5] assigned to var_list. Using the remove() method, we specify the value 3 to be removed from the list. The resulting list becomes [1, 2, 4, 5].

Remove List Items Using Pop Method

The pop() method removes and returns an item from a list based on its index. If no index is provided, it removes the last item.

Example:


# Remove List Items Using Pop Method
var_list = [1, 2, 3, 4, 5]

print(var_list)

popped_item = var_list.pop(2)

print(var_list)
print(popped_item)

Output:


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

In the above-stated example, we have the list [1, 2, 3, 4, 5] assigned to var_list. Using the pop() method with the index 2, we remove the item at that position, which is 3. The resulting list becomes [1, 2, 4, 5], and the removed item is stored in the variable popped_item.

Remove List Items Using Del Statement

The del statement allows you to remove one or more items from a list based on their indices.

Example:


# Remove List Items Using del statement in Python
var_list = [1, 2, 3, 4, 5]

print(var_list)

del var_list[1]

print(var_list)

Output:


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

As shown in the above example, we have the list [1, 2, 3, 4, 5] assigned to var_list. By using the del statement with the index 1, we remove the item at that position, which is 2. The resulting list becomes [1, 3, 4, 5].

These methods offer different approaches to remove items from a list in Python. The choice of method depends on the specific criteria for item removal, such as removing a specific value, removing an item by its index, or removing multiple items at once.

Loop List Items

Looping through list items in Python allows you to iterate over each element in the list and perform certain operations. It enables you to access and process individual items or perform actions based on the values present in the list.

Example:


# iterate list items
var_list = [1, 2, 3, 4, 5]

# Iterate using a for loop
for item in var_list:
    print(item)

print("for loop stops here")
# Iterate using a while loop and index
index = 0
while index < len(var_list):
    print(var_list[index])
    index += 1

Output:


1
2
3
4
5
for loop stops here
1
2
3
4
5

In this example, we have a list [1, 2, 3, 4, 5] assigned to var_list. We demonstrate two common methods for looping through list items:

  1. For Loop: We use a for loop to iterate over each item in the var_list and print its value. The loop variable item takes on each element in the list one by one, allowing you to perform operations on it. This loop continues until all items in the list have been processed.
  2. While Loop with Index: We use a while loop along with an index variable index to iterate through the var_list. The loop continues as long as the index is less than the length of the list. Inside the loop, we access each item using the index and print its value. After each iteration, we increment the index to move to the next item.

Both methods achieve the same result of looping through the list items. The choice of which method to use depends on your specific requirements and the desired way of accessing and processing the list elements.

List Comprehension

List comprehension is a concise and powerful technique in Python to create new lists by iterating over an existing list (or other iterable) and applying an expression or condition. It allows you to create a new list with a more compact syntax compared to traditional loops.

The general syntax of list comprehension is as follows:


var_list = [expression for item in iterable if condition]

Here I explain to you the component of the above syntax:

  • expression: This is the transformation or calculation to be applied to each item in the iterable.
  • item: This represents each element in the iterable that is being iterated over.
  • iterable: This refers to the original list, tuple, string, or any other iterable from which the new list will be created.
  • condition (optional): This is an optional condition that can be applied to filter the elements based on certain criteria. Only the items that meet the condition will be included in the new list.

List comprehension provides a shorter and concise syntax which allow us to perform operations on lists and create new lists in a single line of code.

This type of operation or syntax is useful specially when you need to transform, filter, or process elements from an existing list.

The following example show how to apply list comprehension using the above syntax.

Example:


# List comprehension in Python
var_list_numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

# Squaring each number in the list using list comprehension
# syntax: var_list = [expression for item in iterable if condition]
var_squared_list_numbers = [num**2 for num in var_list_numbers]

print(var_squared_list_numbers)

Output:


[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

In the example provided above, the list comprehension [num**2 for num in var_list_numbers] squares each number in the var_list_numbers list. It iterates over each item (num) in the var_list_numbers list, applies the expression num**2 to square each number, and creates a new list (var_squared_list_numbers) with the squared values.

Such a demonstration shows you how list comprehension can be applied in order to transform and create new lists in a short, concise, and efficient manner way.

List Comprehension Benefits and Usages

When it comes to use lis comprehension we have to know what it provides. In this section I show you several benefits and reasons why it is advantageous to use it in Python:

  1. Concise and Readable Code: List comprehension allows you to express complex operations on lists in a single line of code, making it more concise and readable compared to writing traditional loops.
  2. Efficient Execution: List comprehension leverages the optimized underlying implementation of Python and often performs faster than equivalent for loops, resulting in improved execution speed.
  3. Reduction of Mutable State: By using list comprehension, you can avoid modifying mutable state, such as appending elements to a list within a loop. This can help prevent potential bugs and make your code more robust.
  4. Creation of New Lists: List comprehension allows you to create new lists by transforming or filtering existing ones. It provides a clean and efficient way to generate modified versions of lists without modifying the original data.
  5. Integration with Conditionals: List comprehension supports conditional statements, allowing you to filter elements based on specific conditions. This enables you to include or exclude elements from the new list based on your requirements.
  6. Expressive and Declarative Programming: List comprehension promotes a more declarative style of programming, where you focus on expressing what you want to achieve rather than explicitly implementing the iteration logic. This can make your code more intuitive and easier to understand.

In general, list comprehension is a powerful feature in Python that allows you to write short, concise, efficient, and expressive code for transforming, filtering, and creating new lists. Finally it enhances code readability and can significantly simplify complex list operations.

List Methods

Lists in Python provide various operations and methods to manipulate and work with the data they contain.

For example, if you want to access list elements using their indices, change elements, add new elements, remove elements, sort the list, copy the list, and perform various other operations, you have to use Python list methods that are dedicated to perform such operations and more.

Here I will show you some of the important list methods you can use:

Sort List Items

Sorting a list in Python means arranging its elements in a specific order, such as ascending or descending order. In Python sorting can be done using the sort() method for in-place sorting or the sorted() function to create a new sorted list. The elements of the list must be comparable for sorting to be possible.

The following options are some of the ways you can perform sorting and we also how the sorting operations works in Python:

  1. In-Place Sorting using sort():
    • The sort() method is applied directly to the list and modifies the list itself.
    • The elements of the list are rearranged in ascending order by default.
    • If the list contains elements of different data types, an error may occur unless they are comparable.
    • Example: var_list.sort() sorts var_list in ascending order.
  2. Creating a New Sorted List using sorted():
    • The sorted() function returns a new list with the sorted elements from the original list.
    • The original list remains unchanged.
    • The elements of the list are sorted in ascending order by default.
    • If the list contains elements of different data types, they should be comparable.
    • Example: sorted_list = sorted(var_list) creates a new list sorted_list containing the sorted elements of var_list.

The following example we demonstrate how both in-place sorting and creating a new sorted list work or are performed:

Example:


# Sorting list in Python using sort() method
var_list = [5, 2, 8, 1, 9, 3]

# In-place sorting
var_list.sort()
print(var_list) 

# Creating a new sorted list
var_list = [5, 2, 8, 1, 9, 3, 6, 4, 7]

var_sorted_list = sorted(var_list)
print(var_sorted_list)  

Output:


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

In provided example above, the list var_list is sorted in ascending order both in-place using var_list.sort() and by creating a new sorted list with var_sorted_list = sorted(var_list). The output shows the sorted lists.

Note: Sorting is based on the default comparison logic for the elements. For more complex sorting requirements, you can use the key parameter with custom functions or lambdas to define the sorting criteria.

In Short, sorting lists is useful for various tasks, such as organizing data, finding minimum or maximum values, and preparing data for further analysis or processing.

Copy List Items

If you are a programmer and you are working with lists in Python, you might need to create a copy of a list to perform operations on the copy without modifying the original list. Copying a list ensures that any changes made to one list do not affect the other. There are a few different methods to copy a list in Python, including using slicing, the list() constructor, and the copy() method.

In this article I show you and explain to you several options or different methods to copy list items and they are as follows:

  1. Slicing:
    • Slicing can be used to create a shallow copy of a list by specifying the entire range of indices ([:]).
    • It creates a new list with the same elements as the original list.
    • Example: new_list = old_list[:] creates a copy of old_list named new_list.
  2. Using the list() Constructor:
    • The list() constructor can be used to create a new list by passing an existing list as an argument.
    • It creates a new list with the same elements as the original list.
    • Example: new_list = list(old_list) creates a copy of old_list named new_list.
  3. Using the copy() Method:
    • The copy() method is available for lists and can be used to create a shallow copy of the list.
    • It creates a new list with the same elements as the original list.
    • Example: new_list = old_list.copy() creates a copy of old_list named new_list.

In the following, i show you examples related to these methods:

Method 1: Using Slicing

Example:


# Using Using Slicing to copy list items
original_list = [1, 2, 3, 4, 5, 6, 7, 8, 9]

# Method 1: Slicing
sliced_copy = original_list[:]

print(original_list)    
print(sliced_copy)       

# Copy only some using slicing
sliced_copy = original_list[0:5]

print(sliced_copy)  

Output:


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

Method 2: Using the list() Constructor

Example:


# Using list() constructor to copy list items
original_list = [1, 2, 3, 4, 5, 6, 7, 8, 9]

# Method 2: Using list() constructor
constructor_copy = list(original_list)

print(original_list)      
print(constructor_copy)   

# Modifying the copied lists
constructor_copy[1] = 20

print(constructor_copy) 

Output:


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

Method 3: Using the copy() Method:

Example:


# Using the copy() methodto copy list items
original_list = [1, 2, 3, 4, 5, 6, 7, 8, 9]


# Method 3: Using the copy() method
copy_method_copy = original_list.copy()

print(original_list)     
print(copy_method_copy)   

# Modifying the copied lists
copy_method_copy[2] = 30
print(copy_method_copy) 

Output:


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

Other Method: Using the copy.deepcopy() Method

It is important to note that these methods create a shallow copy of the list, meaning that if the list contains mutable objects (e.g., nested lists), changes made to those objects will be reflected in both the original and copied lists. To create a deep copy, where changes in the original list do not affect the copied list and vice versa, you can use the copy.deepcopy() function from the copy module.

Example:


import copy

# copy using deepcopy() to copy list items
original_list = [1, [2, 3], 4, [5, 6]]

# Creating a deep copy using deepcopy()
deep_copy = copy.deepcopy(original_list)

# Modifying the deep copy
deep_copy[1][0] = 10
deep_copy[3].append(7)

print(original_list) 
print(deep_copy)  

Output:


[1, [2, 3], 4, [5, 6]]
[1, [10, 3], 4, [5, 6, 7]]

In the above example, original_list contains both primitive elements (integers) and nested lists. We use copy.deepcopy() from the copy module to create a deep copy of the list, named deep_copy. The deepcopy() function creates a new list and recursively copies all the elements and sub-elements, ensuring that changes made to the copied list do not affect the original list.

We then modify some elements in the deep copy (deep_copy[1][0] and deep_copy[3]) to demonstrate that these modifications only affect the deep copy, leaving the original list unchanged.

The output shows the original list and the deep copy after the modifications. As you can see, the modifications are isolated to the deep copy, while the original list remains intact.

Join List Items

Joining list items refers to the process of concatenating the elements of a list into a single string or combining multiple lists into a single list. Python provides different methods to join list items based on the desired output.

Here are two common scenarios for joining list items:

  1. Joining List Items into a String:
    • To concatenate the elements of a list into a single string, you can use the join() method of a string.
    • The join() method takes an iterable (such as a list) as its argument and returns a string that is the concatenation of all the elements in the iterable, separated by a specified delimiter.
    • Example: "delimiter".join(list) joins the elements of list into a single string using "delimiter" as the separator.
  2. Combining Multiple Lists into a Single List:
    • To combine multiple lists into a single list, you can use the concatenation operator (+) or the extend() method.
    • The + operator concatenates two or more lists, creating a new list with the combined elements.
    • The extend() method appends the elements of one list to another list, modifying the list in place.
    • Example: list1 + list2 or list1.extend(list2) combines the elements of list1 and list2 into a single list.

In the following example I will show you how to perform both scenarios:

Example:


# Join List Items in Python
var_list_fruits = ["apple", "banana", "orange"]
var_delimiter = ", "

# Joining list items into a string
var_fruits_string = var_delimiter.join(var_list_fruits)

print(var_fruits_string) 

# Combining multiple lists into a single list
var_list_numbers = [1, 2, 3]
var_more_numbers = [4, 5, 6]
var_combined_list = var_list_numbers + var_more_numbers

print(var_combined_list)  

Output:


apple, banana, orange
[1, 2, 3, 4, 5, 6]

The above example, we have shown how to perform join operation in Python. Therefore, the code stated in the above shows that we have a list var_list_fruits containing three fruits. We join the list items into a single string using delimiter.join(var_list_fruits), where var_delimiter is ", ". The resulting string "apple, banana, orange" is stored in the var_fruits_string variable.

We also have two lists, var_list_numbers and var_more_numbers. We combine these lists into a single list using the + operator, resulting in the var_combined_list variable with the elements [1, 2, 3, 4, 5, 6].

These examples demonstrate how to join list items either into a string or into a single list, providing flexibility based on your specific requirements.

Conclusion

In summary, lists are fundamental data structures in Python that allow you to store and manipulate collections of elements. They provide several important characteristics, including order, mutability, and the ability to store duplicate values. Throughout this discussion, we explored various aspects of working with lists in Python, covering topics such as list creation, accessing and modifying list items, adding and removing items, looping through lists, list comprehension, sorting, copying, and joining list items. By understanding these concepts and techniques, you can effectively utilize lists to organize and manipulate data in your Python programs.

For Python beginners and professionals, learning about lists and their operations in Python opens up a world of possibilities for data manipulation and algorithm design. Lists are powerful tools for storing and processing collections of data, and their flexibility allows for a wide range of applications. Whether you are a beginner or an experienced Python programmer, having a strong understanding of lists will greatly enhance your ability to work with data efficiently and elegantly. By leveraging the concepts and techniques discussed in this chat, you can streamline your code, improve its readability, and tackle various programming challenges effectively. So, embrace the power of lists and explore the vast potential they offer in the realm of Python programming.

Categorized in: