Data Structures

Data structures are fundamental to programming as they provide ways to store, organize, and access data effectively. In this unit, we'll explore various data structures in Python, including lists, tuples, and dictionaries. Understanding these structures will enable you to choose the most appropriate one for different tasks, optimize your code's performance, and work with complex data efficiently.

Tuples


A tuple is an ordered, immutable sequence of items. They are most commnoly used to group related data together. Once a tuple is created, its number of elements (length) and the elements themselves cannot be changed.

Key Points:

  • Ordered: Elements in a tuple are stored in a specific order.
  • Immutable: Once a tuple is created, its elements cannot be modified.
  • Heterogeneous: Tuples can contain elements of different data types (e.g., integers, strings, floats, other tuples).

Basics:

  • Tuples are defined using parentheses ().
  • You can access individual elements using indexing.
## TUPLE EXAMPLE ##
my_tuple = (1, 2, 3, "hello", True)

print(my_tuple[3])  # Accesses the fourth element
hello

Tuple Operations:

  • You can extract a portion of a tuple using slicing.
  • You can combine two tuples (concatenation) using the + operator.
  • You can determine the number of elements in a tuple using the len() function.
  • You can unpack tuples into individual variables.
## TUPLE OPERATIONS EXAMPLES ##
my_tuple = (1, "two", 3, "four",5)
print(my_tuple[2:4]) # Extracts elements from index 2 to 3

tuple1 = (1, 2)
tuple2 = (3, 4, 5)
combined_tuple = tuple1 + tuple2 # Concatenation
print(combined_tuple)

print(len(combined_tuple)) # Determine length of the tuple

x, y = tuple1 # Unpacking
print(x)
(3, 'four')
(1, 2, 3, 4, 5)
5
1

Tuples are versatile data structures in Python that offer a balance between flexibility and immutability. They are most commonly used for representating immutable data, returning multiple values from functions, and unpacking values.

Lists


Lists are one of the most versatile data structures in Python. They are ordered collections of items, enclosed in square brackets []. Unlike tuples, lists are mutable, meaning you can change their elements after creation.

Key Points:

  • Ordered: Elements in a list are stored in a specific order.
  • Mutable: You can add, remove, or modify elements in a list.
  • Heterogeneous: Lists can contain elements of different data types.

Basics:

  • Lists are defined using brackets [].
  • You can access individual elements using indexing.
## LIST EXAMPLE ##
my_list = [1, 2, 3, "hello", True]

print(my_list[2])  # Accesses the third element
3

List Operations:

  • You can extract a portion of a list using slicing.
  • You an append an element to the end of a list.
  • You can insert an element at a specific index.
  • You can remove an element by value or index.
  • You can combine two lists (concatenation) using the + operator.
  • You can determine the number of elements in a list using the len() function.
## LIST OPERATIONS EXAMPLES ##
my_list = [1, "two", 3, "four", 5]
print(my_list[2:4]) # Extracts elements from index 2 to 3

my_list.append("six") # Append "six" to the end of the list
print(my_list)

my_list.insert(0,"zero") # Insert "zero" at index 0
print(my_list)

my_list.remove("two") # Remove the first occurence of the value "two"
del my_list[2] # Remove the value at index 2
print(my_list)

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

print(len(combined_list)) # Determine length of the list

x, y = list1
print(x)
[3, 'four']
[1, 'two', 3, 'four', 5, 'six']
['zero', 1, 'two', 3, 'four', 5, 'six']
['zero', 1, 'four', 5, 'six']
[1, 2, 3, 4, 5]
5
1

Lists are a powerful data structure in Python, allowing you to store and manipulate collections of data efficiently. Their versatility makes them a fundamental tool for many programming tasks.

Dictionaries


A dictionary is an unordered collection of key-value pairs. It's a versatile data structure that allows you to store and retrieve data efficiently using keys.

Key Points:

  • Unordered: Elements in a list are stored in a specific order.
  • Mutable: You can add, remove, or modify elements in a list.
  • Keys Must Be Unique: Each key in a dictionary must be unique.
  • Keys Can Be of Various Types: Keys can be strings, numbers, or tuples.

Basics:

  • Lists are defined using braces {}.
  • You can access values using their corresponding keys.
## DICTIONARY EXAMPLE ##
my_dict = {"name": "Milo", "age": 35, "city": "Orange"}

print(my_dict["name"])  # Accesses the value with a key of "name"
Milo

Dictionary Operations:

  • You can add/modify key-value pairs.
  • You can remove key-value pairs.
  • You can retrieve a list of the keys using the keys() method.
  • You can retrieve a list of the values using the values() method.
  • You can retrieve a list of the key-value pairs using the items() method.
  • You can remove all items from a dictionary using the clear() method.
## DICTIONARY OPERATIONS EXAMPLES ##
my_dict = {'a': 1, 'b': 2, 'c': 3}

my_dict["d"] = 4  # Adds a new key-value pair
my_dict["a"] = 0  # Modifies the value with the key "a"

del my_dict["c"]  # Removes the key-value pair with the key "c"

print(my_dict.keys()) # Get all keys

print(my_dict.values())  # Get all values
 
print(my_dict.items())  # Get key-value pairs

my_dict.clear()  # Clear the dictionary
print(my_dict.items())
dict_keys(['a', 'b', 'd'])
dict_values([0, 2, 4])
dict_items([('a', 0), ('b', 2), ('d', 4)])
dict_items([])

Dictionaries are a powerful data structure in Python for storing and retrieving data efficiently. They are widely used in various programming tasks, from simple data organization to complex data modeling.