CodeGym /Java Course /Python SELF EN /Practical Work with Lists

Practical Work with Lists

Python SELF EN
Level 7 , Lesson 9
Available

9.1 Creating a Copy of a List

Creating a copy of a list in Python is a big deal when you want to avoid unexpected changes to your data while messing around with lists. It's key to get the difference between shallow copying and deep copying.

Shallow Copying

A shallow copy makes a new list, but the elements are still the same (if the elements are references, they're copied as references). You can do this a few ways:

Using list() function:


original = [1, 2, 3]
copy = list(original)

Using Slicing:


original = [1, 2, 3]
copy = original[:]

copy() method:

Deep Copying

Deep copying makes a new list and also creates copies of all nested objects. This is super crucial when lists have other mutable data types, like other lists. For this, you use the copy module:


import copy
original = [[1, 2], [3, 4]]
deep_copy = copy.deepcopy(original)

When to Use Each Method

Shallow copying is faster and works when the list items are simple and don't need duplication (like strings or numbers). Go for deep copying when the list items are mutable collections themselves or when changes in the copy shouldn't mess with the original.

9.2 Removing an Element from a List

Here's a fun one: removing element(s) from a list inside a loop.

When looping through a list with a for loop, the list hands over a special object — an iterator, which the for loop uses to go over all the elements. If you yank an element out of the list while using the iterator [by a for loop], the iterator can go haywire.

Like, if you delete the 3rd item, the 4th one automatically turns into the 3rd. But, the for loop, through the iterator, will switch to the new 4th item, which was originally the 5th. So, the 4th item is skipped.

Here are some safe ways to remove elements:

Using remove() method

If you know exactly which item to delete, you can use remove() in the loop. But this could be slow if you've got lots of items since each remove() call searches for the item before removing it, which bogs things down.

Creating a New List

A safer bet — make a new list with only the items you want to keep:


original_list = [1, 2, 3, 4, 5, 6]
new_list = [x for x in original_list if x % 2 != 0]  # keeping only odd numbers

Using Indices

You can use a for loop with reverse indexing to remove elements without skipping any:


for i in range(len(original_list) - 1, -1, -1):
    if original_list[i] % 2 == 0:  # condition for removal
        del original_list[i]

By going through the list backwards, the indices of the already checked elements are the only ones that change.

Using a Copy of the List:

Say you want to remove all negative numbers from a list:


numbers = [1, -1, 2, -2, 3, -3]
# Create a copy of the list for safe iteration
for number in numbers.copy():
    if number < 0:
        numbers.remove(number)
print(numbers) # Outputs [1, 2, 3]

9.3 Merging Lists

Lots of times you need to join two or more lists into one. There are a bunch of ways to do this, each good for different things and having its quirks.

Using the + Operator

The easiest way to merge two lists is by using the + operator. It's straightforward and makes sense:


list1 = [1, 2, 3]
list2 = [4, 5, 6]
combined_list = list1 + list2
print(combined_list)  # Outputs [1, 2, 3, 4, 5, 6]

extend() Method

The extend() method changes the first list by tacking on all the elements of the second list to its end. This alters the original list:


list1 = [1, 2, 3]
list2 = [4, 5, 6]
list1.extend(list2)
print(list1)  # Outputs [1, 2, 3, 4, 5, 6]

List Comprehensions

List comprehensions can be used to create new lists by merging elements from multiple lists into one complex list:


list1 = [1, 2, 3]
list2 = [4, 5, 6]
combined_list = [item for sublist in [list1, list2] for item in sublist]
print(combined_list)  # Outputs [1, 2, 3, 4, 5, 6]

append() Method

You could add all elements from the second list to the first one. Just another option.


list1 = [1, 2, 3]
list2 = [4, 5, 6]
for x in list2:
    list1.append(x)
print(list1)  # Outputs [1, 2, 3, 4, 5, 6]

Basically, that's all I wanted to share with you about lists 😊

2
Task
Python SELF EN, level 7, lesson 9
Locked
Sorting Without Sorting
Sorting Without Sorting
2
Task
Python SELF EN, level 7, lesson 9
Locked
Clean the list
Clean the list
1
Опрос
Lists in Python,  7 уровень,  9 лекция
недоступен
Lists in Python
Lists in Python
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION