Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

Python List Fundamentals and Operations

Tech 1

An empty list can be defined using square brackets [] or the built-in list() function.

container = list()  # or container = []
container.append(1)
print(container)  # Output: [1]

Lists can hold various data types and can be nested. To access elements in a nested list, use multiple indices.

nested_data = [['apple', 'banana'], [100, 200, 300]]
print(nested_data[0][1])  # Output: banana

Modifying a value is done by assigning a new value to a specific index.

List Operations

Positive Index Slicing

Slicing uses the syntax sequence[start:end:step], with a default step of 1. The slice is "left-closed, right-open".

numbers = [0, 1, 2, 3, 4, 5]
print(numbers[1:3])   # Output: [1, 2]
print(numbers[:3])    # Output: [0, 1, 2]
print(numbers[2:])    # Output: [2, 3, 4, 5]

Negative Index Slicing

Negative indices count from the end of the list.

numbers = [0, 1, 2, 3, 4, 5]
print(numbers[-1])    # Output: 5
print(numbers[-3])    # Output: 3
print(numbers[0:-1])  # Output: [0, 1, 2, 3, 4]

Values at these indices can be modified directly.

List Concatenation, Replication, and Membership

Operator Description Example Result
+ Concatenates two lists [1, 2] + [3, 4] [1, 2, 3, 4]
* Replicates a list [0] * 3 [0, 0, 0]
in Checks for membership 5 in [1, 5, 9] True
not in Checks for non-membership 3 not in [1, 5, 9] True

Adding Elements

append() Method

Adds a single element to the end of the list.

data = [0, 1]
data.append(3)
print(data)  # Output: [0, 1, 3]
data.append([2, 4])
print(data)  # Output: [0, 1, 3, [2, 4]]

extend() Method

Adds each element from an iterable to the end of the list. The argument must be iterable.

data = [0, 1]
data.extend([3, 2, 4])
print(data)  # Output: [0, 1, 3, 2, 4]

It works with various iterables like tuples, strings, etc.

data = [0, 1]
my_dict = {'key1': 10, 'key2': 20}
data.extend(my_dict)  # Extends with dictionary keys
print(data)  # Output: [0, 1, 'key1', 'key2']

insert() Method

Inserts an element at a specified index.

items = [0, 1, 2, 3]
items.insert(1, 99)
print(items)  # Output: [0, 99, 1, 2, 3]

Removing Elements

pop() Method

Removes and returns an element at a given index. Defaults to the last element.

values = [0, 1, 2, 3, 4, 5]
last_val = values.pop()
print(values)    # Output: [0, 1, 2, 3, 4]
print(last_val)  # Output: 5
second_val = values.pop(1)
print(values)     # Output: [0, 2, 3, 4]
print(second_val) # Output: 1

remove() Method

Removes the first occurrence of a specified value. Raises an error if the value is not found.

animals = ['cat', 'bat', 'cat', 'rat']
animals.remove('cat')
print(animals)  # Output: ['bat', 'cat', 'rat']

del Statement

Deletes an element at a specific index.

creatures = ['dragon', 'unicorn', 'griffin']
del creatures[1]
print(creatures)  # Output: ['dragon', 'griffin']

Sorting

sort() Method

Sorts the list in-place. Set reverse=True for descending order.

nums = [2, 5, 3.14, 1, -7]
nums.sort()
print(nums)  # Output: [-7, 1, 2, 3.14, 5]
nums.sort(reverse=True)
print(nums)  # Output: [5, 3.14, 2, 1, -7]

reverse() Method

Revreses the list in-place.

nums = [2, 5, 3.14, 1, -7]
nums.reverse()
print(nums)  # Output: [-7, 1, 3.14, 5, 2]

Programming Practices

Removing Duplicates

Using a Set

Convert the list to a set to remove duplicates, then back to a list. Note that this does not preserve order.

source = [0,1,1,1,2,2,3,4,5,5,6,5,3,2,4,6,8,9,2,5]
unique_items = list(set(source))

Using a Loop

Iterate through the list and build a new list with unique elements.

source = [0,1,1,1,2,2,3,4,5,5,6,5,3,2,4,6,8,9,2,5]
result_collection = []
for element in source:
    if element not in result_collection:
        result_collection.append(element)

Related Articles

Understanding Strong and Weak References in Java

Strong References Strong reference are the most prevalent type of object referencing in Java. When an object has a strong reference pointing to it, the garbage collector will not reclaim its memory. F...

Comprehensive Guide to SSTI Explained with Payload Bypass Techniques

Introduction Server-Side Template Injection (SSTI) is a vulnerability in web applications where user input is improper handled within the template engine and executed on the server. This exploit can r...

Implement Image Upload Functionality for Django Integrated TinyMCE Editor

Django’s Admin panel is highly user-friendly, and pairing it with TinyMCE, an effective rich text editor, simplifies content management significantly. Combining the two is particular useful for bloggi...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.