Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

Core Data Structures in Python: Lists, Tuples, and Dictionaries

Tech May 9 3

Overview of Sequences

Python provides several sequence types, with strings, lists, and tuples being the most common. Lists and tuples share similar syntax but differ fundamentally in mutability: tuple are immutable once defined, while lists can be modified dynamically.

Creating Lists and Tuples

Lists are defined using square brackets [], while tuples use parentheses ().

# Creating a list
collection_list = ['data_science', 42, 'python']
print(collection_list)

# Creating a tuple
collection_tuple = ('data_science', 42, 'python')
print(collection_tuple)

Sequence Fundamentals

Indexing

Both structures support zero-based indexing. Lists allow element reassignment, but tuples do not, as they act as constants.

items = (10, 'alpha', 3.14, 'beta', -5)
print(items[0])    # First element
print(items[-1])   # Last element

Slicing

Use the [start:end:step] syntax to extract sub-sequences. Negative indices count backward from the end.

values = (0, 10, 20, 30, 40)
print(values[1:3])   # (10, 20)
print(values[-3:-1]) # (20, 30)

Concatenation and Repetition

Sequences can be combined using the + operator and repeated with the * operator. Note that you must combine like types.

# Concatenation
combined = (1, 2) + (3, 4)

# Repetition
repeated = ['x'] * 5

Note: To define a single-item tuple, you must include a trailing comma: ('singleton',).

Advanced Sequence Operations

Python provides built-in functions such as len(), max(), and min(). For max() and min() to function, all elements within the sequence must be of comparable types.

Sequence Packing and Unpacking

Packing occurs when multiple values are asssigned to a single variable, creating a tuple. Unpacking extracts sequence elements into individual variables.

# Packing
metrics = 100, 200, 300

# Unpacking with asterisk for remainder
first, *others = [1, 2, 3, 4]
print(first)  # 1
print(others) # [2, 3, 4]

Manipulating Lists

Beyond basic construction, use list() to convert other iterables into lists. Modify contents using append() for single items, extend() for bulk addition, and del or remove() for deletion.

container = [1, 2, 3]
container.append(4)         # Add to end
container.insert(0, 0)      # Insert at index
container[1:3] = [9, 9]     # Slice assignment

Dictionary Mappings

Dictionaries store data as key-value pairs. Keys must be immutable (e.g., strings, numbers, or tuples), while values can be any object. Keys must be unique.

# Dictionary creation
user_data = {'id': 101, 'status': 'active'}

# Accessing and modifying
print(user_data['id'])
user_data['status'] = 'inactive'

# Removing a key
del user_data['id']

Useful Dictionary Methods

  • get(key): Safely retrieves a value; returns None instead of raising a KeyError if the key is missing.
  • update(other_dict): Merges another dictionary into the current one.
  • keys(), values(), and items(): Return views of the dictionary's contents, which can be cast to lists.

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.