Python Data Structures

0
363

Here’s a structured explanation of Python Data Structures covering the subtopics you mentioned:

1. Lists

Lists are mutable sequences used to store collections of items.

List Methods

  • append(item): Adds an item to the end of the list.
  • extend(iterable): Adds all elements from an iterable to the list.
  • insert(index, item): Inserts an item at the specified position.
  • remove(item): Removes the first occurrence of an item.
  • pop(index): Removes and returns the item at the given index (defaults to the last item).
  • index(item): Returns the index of the first occurrence of an item.
  • count(item): Returns the count of occurrences of an item.
  • sort(): Sorts the list in ascending order.
  • reverse(): Reverses the elements of the list.

List Slicing

my_list = [10, 20, 30, 40, 50]
print(my_list[1:4])  # Output: [20, 30, 40]
print(my_list[:3])   # Output: [10, 20, 30]
print(my_list[::2])  # Output: [10, 30, 50]
print(my_list[::-1]) # Output: [50, 40, 30, 20, 10] (Reversed List)

List Comprehensions

List comprehensions provide a concise way to create lists.

squared_numbers = [x**2 for x in range(5)]
print(squared_numbers)  # Output: [0, 1, 4, 9, 16]

even_numbers = [x for x in range(10) if x % 2 == 0]
print(even_numbers)  # Output: [0, 2, 4, 6, 8]

2. Tuples (Immutable Sequences)

Tuples are immutable sequences that store heterogeneous data.

my_tuple = (10, 20, 30, "Hello")
print(my_tuple[1])  # Output: 20

Tuple Packing & Unpacking

a, b, c = (1, 2, 3)  # Unpacking
print(a, b, c)  # Output: 1 2 3

packed_tuple = 10, 20, 30  # Packing
print(packed_tuple)  # Output: (10, 20, 30)

Why Tuples?

  • More memory-efficient than lists.
  • Used as dictionary keys (since they are immutable).
  • Ensures data integrity by preventing modifications.

3. Sets (Unique Elements, Operations)

Sets are unordered collections of unique elements.

Set Operations

set1 = {1, 2, 3, 4}
set2 = {3, 4, 5, 6}

print(set1 | set2)  # Union: {1, 2, 3, 4, 5, 6}
print(set1 & set2)  # Intersection: {3, 4}
print(set1 - set2)  # Difference: {1, 2}
print(set1 ^ set2)  # Symmetric Difference: {1, 2, 5, 6}

Set Methods

  • add(item): Adds an item to the set.
  • remove(item): Removes an item (throws an error if not found).
  • discard(item): Removes an item (no error if not found).
  • pop(): Removes and returns an arbitrary element.
  • clear(): Removes all elements.

4. Dictionaries (Key-Value Pairs, Methods)

Dictionaries store data in key-value pairs.

student = {"name": "Alice", "age": 20, "grade": "A"}
print(student["name"])  # Output: Alice

Dictionary Methods

  • keys(): Returns a list of keys.
  • values(): Returns a list of values.
  • items(): Returns key-value pairs.
  • get(key, default): Returns the value for a key or a default value.
  • update(dict2): Updates with another dictionary’s key-value pairs.
  • pop(key): Removes and returns the value of the key.
  • popitem(): Removes and returns the last inserted key-value pair.
student["age"] = 21  # Modifying a value
student["city"] = "New York"  # Adding a new key-value pair

for key, value in student.items():
    print(f"{key}: {value}")

5. Strings (Methods, Formatting, Encoding)

Strings are immutable sequences of characters.

String Methods

  • upper(), lower(), title(): Changes case.
  • strip(), lstrip(), rstrip(): Removes whitespace.
  • find(substring): Returns the index of the first occurrence.
  • replace(old, new): Replaces substrings.
  • split(delimiter): Splits the string into a list.
  • join(iterable): Joins elements with a separator.
text = " hello world "
print(text.strip())  # Output: "hello world"
print(text.upper())  # Output: " HELLO WORLD "
print("Python".join(["Hello", "World"]))  # Output: "HelloPythonWorld"

String Formatting

name = "Alice"
age = 25
print(f"My name is {name} and I am {age} years old.")  # f-strings
print("My name is {} and I am {} years old.".format(name, age))  # format()

String Encoding

text = "Hello"
encoded_text = text.encode("utf-8")
print(encoded_text)  # Output: b'Hello'
decoded_text = encoded_text.decode("utf-8")
print(decoded_text)  # Output: Hello

This overview provides a strong foundation in Python Data Structures. Let me know if you need deeper explanations! 

Rechercher
Sellect from all Catégories bellow ⇓
Lire la suite
Python
Introduction to Python
Python is a high-level, interpreted programming...
Par flowisetech 2025-03-02 16:20:11 0 372
HTML
How to Create a Responsive Navbar With Additional Features Like Submenus, Animations, And a Dark Mode toggle
Creating a responsive navbar with additional...
Par flowisetech 2025-02-21 12:00:15 0 403
Java
Introduction to Java
Java is a widely-used, object-oriented,...
Par flowisetech 2025-02-14 19:23:16 0 458
Social Media
How to Make Money on WhatsApp: A Step-by-Step Guide
Making money from WhatsApp can be highly...
Par flowisetech 2025-02-24 08:32:37 0 329
Programming Languages
Deference between PHP and HTML
PHP and HTML serve different purposes in web...
Par Nicholas 2025-01-25 13:38:09 0 691