Introduction to Software Systems
  • About
  • Introduction
  • Software Engineering
    • Software System
    • Software Product Development
    • Computer Networks
  • Terminal Programming
    • BASH - Basic Commands
    • BASH - Conditions and Loops
    • Worked-out Examples
    • Practice Questions
  • Databases
    • Structured Databases
      • SQL Queries
      • Worked-out Example
    • Unstructured Databases
      • NoSQL Queries
      • Worked-out Example
  • Object Oriented Programming
    • Python - Introduction
    • Python - Basic Concepts
    • Python - Inbuilt Datastructures
    • Python - Conditions and Loops
    • Python - Lambda, Functions, Class/Objects
    • Worked-out Examples
  • WEB TECHNOLOGIES
    • HTML
    • CSS
    • Native JavaScript - Basics
    • Native JavaScript - Conditional Statements and Loops
    • Native JavaScript - Data Structures
    • JavaScript - Scope, Functions, Type Conversion
Powered by GitBook
On this page
  • Lists
  • Tuple
  • Sets
  • Dictionaries
  1. Object Oriented Programming

Python - Inbuilt Datastructures

Lists

In Python, a list is a versatile, built-in data type that holds an ordered collection of items, which can be of different data types. Lists are mutable, meaning you can change their contents after creation.

Creating Lists:

  • Lists are created using square brackets []

    mylist = ["apple", "banana", "cherry"]
  • You can also use the list() constructor to create a list

    thislist = list(("apple", "banana", "cherry")) 
    # note the double round-brackets
  • Lists can store various data types, including strings, integers, and even other lists

    list1 = ["abc", 34, True, 40, "male"]

Basic List Operations:

  • Accessing Elements: List items are indexed, starting at 0. You can access elements using square brackets and their index. Negative indexing accesses elements from the end of the list

    list=["Student", "Teacher", "Parent", 1, 5, 6, 8]
    print(list[0])  # Output: Student
    print(list[-1]) # Output: 8
  • Slicing: You can extract a portion of a list by specifying a range of indexes

    print(list[2:5]) # Output: ['Parent', 1, 5]
  • Length: Use the len() function to determine the number of items in a list

    thislist = ["apple", "banana", "cherry"]
    print(len(thislist)) # Output: 3

Modifying Lists:

  • Adding Items:

    • append(): Adds an element to the end of the list

      list = ['larry', 'curly', 'moe']
      list.append('shemp')
      print(list) # Output: ['larry', 'curly', 'moe', 'shemp']
    • insert(): Inserts an element at a specific index

      list.insert(0, 'xxx')
      print(list) # Output: ['xxx', 'larry', 'curly', 'moe', 'shemp']
    • extend(): Adds elements from another list to the end of the current list

      list.extend(['yyy', 'zzz'])
      print(list) 
      # Output: ['xxx', 'larry', 'curly', 'moe', 'shemp', 'yyy', 'zzz']
  • Removing Items:

    • remove(): Removes the first occurrence of a specified value

      list.remove('curly')
      print(list) # Output: ['xxx', 'larry', 'moe', 'shemp', 'yyy', 'zzz']
    • list.pop(1)
      print(list) # Output: ['xxx', 'moe', 'shemp', 'yyy', 'zzz']

Other Useful List Operations:

  • index(): Returns the index of the first occurrence of a value.

  • sort(): Sorts the list in ascending order.

  • in: Tests if a value is in the list.

Lists are a fundamental part of Python, offering a flexible way to work with ordered data

Tuple

In Python, a tuple is an ordered collection of items, similar to a list. However, tuples are immutable, meaning their contents cannot be changed after creation. This immutability makes tuples suitable for storing fixed collections of data

Creating Tuples:

  • Tuples are created by placing a sequence of values separated by commas within round brackets ()

    my_tuple = (1, 2, 3, 4, 5)
    print(my_tuple) # Output: (1, 2, 3, 4, 5)
  • Tuples can contain heterogeneous data types, including numbers, strings, and other tuples

    mixed_tuple = (2, 'Hello', 'Python')
    print(mixed_tuple) # Output: (2, 'Hello', 'Python')
  • To create a tuple with a single element, include a comma after the item

    single_tuple = ("apple",)
    print(single_tuple) # Output: ('apple',)
  • An empty tuple is created with empty parentheses

    empty_tuple = ()
    print(empty_tuple) # Output: ()

Basic Tuple Operations:

  • Accessing Elements: Tuple items are accessed by their index, starting from 0

    my_tuple = ("apple", "banana", "cherry")
    print(my_tuple[0])  # Output: apple
  • Slicing: You can extract a portion of a tuple by specifying a range of indices.

    my_tuple = (1, 2, 3, 4, 5)
    print(my_tuple[1:4])  # Output: (2, 3, 4)
  • Length: The len() function returns the number of elements in a tuple

    my_tuple = (1, 2, 3)
    print(len(my_tuple))  # Output: 3
  • Concatenation: Tuples can be concatenated using the + operator

    tuple1 = (1, 2, 3)
    tuple2 = (4, 5, 6)
    combined_tuple = tuple1 + tuple2
    print(combined_tuple) # Output: (1, 2, 3, 4, 5, 6)

Tuple Methods:

  • count(): Returns the number of times a specified value occurs in a tuple

    my_tuple = (1, 2, 2, 3, 2)
    print(my_tuple.count(2))  # Output: 3
  • index(): Returns the index of the first occurrence of a specified element in a tuple

    fruits = ("apple", "banana", "orange", "apple", "kiwi", "apple")
    kiwi_index = fruits.index("kiwi")
    print("Index of 'kiwi' in the tuple: ", kiwi_index) 
    # Output: Index of 'kiwi' in the tuple:  4

Other Tuple Operations and Characteristics:

  • Immutability: Once a tuple is created, its contents cannot be modified

  • Tuple Packing and Unpacking: Tuple packing involves placing multiple values into a tuple, while unpacking involves extracting those values back into individual variables

  • Tuples as Dictionary Keys: Tuples can be used as keys in dictionaries because they are immutable

  • Iteration: You can iterate through a tuple using a for loop

  • tuple() function: Used to convert a list, set, or any iterable object into a tuple

    my_list = [1, 2, 3, 4, 5]
    my_tuple = tuple(my_list)
    print(my_tuple) # Output: (1, 2, 3, 4, 5)
  • max(): The max() function is used to return the maximum value in a tuple

  • min(): The min() function is used to return the minimum value in a tuple

  • sum(): The sum() function is used to return the sum of all elements in a tuple

Tuples are useful when you want to ensure that data remains constant throughout the program

Sets

In Python, a set is a built-in data structure used to store an unordered collection of unique items. Sets are similar to mathematical sets and support operations like union, intersection, and difference

Defining a Set:

  • A set is created using curly braces {} or the built-in set() function

  • Sets are unordered, so the items do not have a defined order

  • Sets are unindexed, so you cannot access items using an index

  • Sets only store unique elements; duplicate values are not allowed

  • Set elements must be of an immutable type, such as strings, numbers, or tuples

Creating Sets:

  • Using curly braces:

    my_set = {1, 2, 3}
  • Using the set() constructor:

    my_set = set([1, 2, 3])

Basic Set Operations:

  • Adding Items: Although sets are immutable, items can be added.

    • add(): Adds a single element to the set.

      my_set = {1, 2}
      my_set.add(3)
      print(my_set)  # Output: {1, 2, 3}
    • update(): Adds multiple elements from an iterable (like a list or another set) to the set.

      my_set = {1, 2}
      my_set.update([3, 4, 5])
      print(my_set)  # Output: {1, 2, 3, 4, 5}
  • Removing Items: Although sets are immutable, items can be removed.

    • remove(): Removes a specified element from the set. Raises an error if the element is not found.

      my_set = {1, 2, 3}
      my_set.remove(2)
      print(my_set)  # Output: {1, 3}
    • discard(): Removes a specified element from the set if it is present. Does not raise an error if the element is not found.

      my_set = {1, 2, 3}
      my_set.discard(4)
      print(my_set)  # Output: {1, 2, 3}
    • pop(): Removes and returns an arbitrary element from the set. Raises an error if the set is empty.

      my_set = {1, 2, 3}
      element = my_set.pop()
      print(my_set)  # Output: {2, 3} (or some other order)
      print(element) # Output: 1 (or some other element)
    • clear(): Removes all elements from the set.

      my_set = {1, 2, 3}
      my_set.clear()
      print(my_set)  # Output: set()

Set Operations:

  • Union: Returns a new set containing all elements from both sets.

    set1 = {1, 2, 3}
    set2 = {3, 4, 5}
    union_set = set1.union(set2)
    print(union_set)  # Output: {1, 2, 3, 4, 5}
  • Intersection: Returns a new set containing only the elements common to both sets

    set1 = {1, 2, 3}
    set2 = {3, 4, 5}
    intersection_set = set1.intersection(set2)
    print(intersection_set)  # Output: {3}
  • set1 = {1, 2, 3}
    set2 = {3, 4, 5}
    difference_set = set1.difference(set2)
    print(difference_set)  # Output: {1, 2}
  • set1 = {1, 2, 3}
    set2 = {3, 4, 5}
    symmetric_difference_set = set1.symmetric_difference(set2)
    print(symmetric_difference_set)  # Output: {1, 2, 4, 5}
  • Subset and Superset:

    • issubset(): Checks if one set is a subset of another.

    • issuperset(): Checks if one set is a superset of another.

Other operations:

  • len(): to find the length of a set.

  • in: Tests if a value is in the set.

Sets are commonly used for tasks such as removing duplicates from a collection, membership testing, and performing mathematical set operations.

Dictionaries

In Python, a dictionary is a versatile and mutable data structure that stores collections of key-value pairs. Dictionaries are used for efficient data retrieval, where each unique key maps to an associated value.

Key Characteristics:

  • Key-Value Pairs: Each item in a dictionary is a mapping between a key and a value

  • Keys Must Be Unique: Within a dictionary, each key must be distinct

  • Mutable: Dictionaries can be modified after creation, allowing you to add, update, and delete key-value pairs

  • Ordered: Dictionaries preserve the order in which items are inserted (starting with Python 3.7)

  • Keys Must Be Hashable: Keys should be of an immutable type (e.g., numbers, strings, tuples)

Creating Dictionaries:

  • Using Dictionary Literals: Enclose key-value pairs within curly braces {}

    my_dict = {"key1": "value1", "key2": "value2"}
  • Using the dict() Constructor: Create dictionaries from iterables of key-value pairs, other mappings, or keyword arguments

    # From a list of tuples
    my_dict = dict([("key1", "value1"), ("key2", "value2")])
    
    # Using keyword arguments
    my_dict = dict(key1="value1", key2="value2")

Basic Dictionary Operations:

  • my_dict = {"name": "Alice", "age": 30}
    print(my_dict["name"])  # Output: Alice
  • Adding/Updating Items: Add a new key-value pair or update an existing value by assigning a value to a key.

    my_dict["city"] = "New York"  # Adds a new key-value pair
    my_dict["age"] = 31           # Updates the value for the key "age"
  • Deleting Items: Remove key-value pairs from a dictionary.

    • pop(): Removes the item with the specified key.

    • clear(): Remove all the items from the dictionary.

Dictionary Methods:

  • keys(): Returns a view of all the keys in the dictionary.

  • values(): Returns a view of all the values in the dictionary.

  • items(): Returns a view of all key-value pairs as tuples.

  • get(key, default): Returns the value for a key. If the key does not exist, it returns the default value (or None if no default is specified).

  • update(other_dict): Merges the key-value pairs from other_dict into the dictionary. If a key exists in both dictionaries, the value from other_dict overwrites the value in the original dictionary.

  • copy(): Returns a shallow copy of the dictionary.

Dictionary Comprehension:

  • numbers = [1, 2, 3, 4, 5]
    squared_dict = {number: number**2 for number in numbers}
    print(squared_dict)  # Output: {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}

Dictionaries are widely used in Python for tasks such as storing configuration settings, representing data structures (e.g., JSON), and implementing caching mechanisms. They provide efficient ways to organize and access data using key-value relationships.

PreviousPython - Basic ConceptsNextPython - Conditions and Loops

Last updated 3 months ago

pop(): Removes and returns the element at a given index. If no index is specified, it removes and returns the last element.

copy(): Returns a copy of the list. Assignment with = does not copy the list, it makes the two variables point to the one list in memory.

Difference: Returns a new set containing elements present in the first set but not in the second set.

Symmetric Difference: Returns a new set containing elements present in either set, but not in both.

Accessing Values: Retrieve a value by its key using square brackets [].

Create new dictionaries based on existing iterables using a concise syntax.

4
1
2
2
1
1