DEV Community

Cover image for 🎁Learn Python in 10 Days: Day5
William
William

Posted on

🎁Learn Python in 10 Days: Day5

Today, we're continuing our 10-day journey to learn Python, kicking off Day 5's lesson. If you haven't checked out Day 1 yet, you can find it here: 🎁Learn Python in 10 Days: Day 1

Day 5: Introduction to Data Containers 🎉

A data container is a type of data structure that can hold multiple pieces of data, where each piece is referred to as an element. Elements can be of any data type, such as strings, numbers, booleans, etc.

Data containers are categorized based on certain features, such as:

  • Whether they support duplicate elements
  • Whether they are mutable
  • Whether they are ordered or unordered

The five main types of data containers are:

  • Lists
  • Tuples
  • Strings
  • Sets
  • Dictionaries

Data Container: List

List Overview:

The list type is a container that can store multiple data items at once.

Basic Syntax:

# Literal
[Element1, Element2, Element3, ...]

# Define variable
variable_name = [Element1, Element2, Element3, ...]

# Define an empty list
variable_name = []

variable_name = list()
Enter fullscreen mode Exit fullscreen mode

Each piece of data in a list is called an element and is separated by a comma.

# List
languages = ['python', 'c', 'c++', 'java']
print(languages)
print(type(languages))

# Nested list
nested_list = [[1, 2, "damn it"], [4, 5, True]]
print(nested_list)
print(type(nested_list))
Enter fullscreen mode Exit fullscreen mode

Note: Lists can store multiple data items of different types and support nesting.

List Indexing:

You can access specific elements in a list using index notation.

# List indexing
names = ["tom", "jack", "alex"]
print(names[0])  # Output: tom
print(names[1])  # Output: jack
print(names[2])  # Output: alex
Enter fullscreen mode Exit fullscreen mode

Reverse indexing is also supported:

names = ["tom", "jack", "alex"]
print(names[-3]) # Output: tom
print(names[-2]) # Output: jack
print(names[-1]) # Output: alex
Enter fullscreen mode Exit fullscreen mode

For nested lists:

# Nested list indexing
nested_list = [[1, 2, "damn it"], [4, 5, True]]
print(nested_list[1][2])  # Output: True
print(nested_list[0][2])  # Output: damn it
Enter fullscreen mode Exit fullscreen mode

Note: Do not try to access indexes out of range; it will cause an IndexError.

Common List Operations:

  1. Insert an element
  2. Delete an element
  3. Clear elements
  4. Modify elements
  5. Count elements

These operations are referred to as methods of the list.

  1. List Query Functionality: Find the index of a specified element. If not found, it raises a ValueError.
   # Query index
   languages = ['python', 'c', 'c++', 'java']
   index = languages.index("python")
   print(f"Index of 'python': {index}")
Enter fullscreen mode Exit fullscreen mode
  1. Modify Elements: Modify the value at a specific index.
   # Modify elements
   my_list = [1, 2, 3, 4]
   my_list[0] = 8
   print(my_list)
   my_list[-1] = 6
   print(my_list)
Enter fullscreen mode Exit fullscreen mode
  1. Insert Elements:
   # Insert elements
   my_list = [1, 2, 3, 4]
   my_list.insert(2, 'damn it')
   print(my_list)
Enter fullscreen mode Exit fullscreen mode
  1. Append Elements:
   # Append elements
   my_list = [1, 2, 3, 4]
   my_list.append(4)  # Output: [1, 2, 3, 4, 4]
   print(my_list)
   my_list.append([5, 5, 6])
   print(my_list)  # Output: [1, 2, 3, 4, 4, [5, 5, 6]]
Enter fullscreen mode Exit fullscreen mode
  1. Extend a List:
   # Extend a list
   my_list = [1, 2, 3, 4]
   my_list.extend([4, 5, 6])
   print(my_list)  # Output: [1, 2, 3, 4, 4, 5, 6]
Enter fullscreen mode Exit fullscreen mode
  1. Delete Elements:
   # Delete elements
   my_list = [1, 2, 3, 4]
   del my_list[0]
   print(my_list)  # Output: [2, 3, 4]

   my_list.pop(0)
   print(my_list)  # Output: [3, 4]
Enter fullscreen mode Exit fullscreen mode
  1. Remove a Specific Element:
   # Remove a specific element
   my_list = [1, 2, 3, 2]
   my_list.remove(2)
   print(my_list)  # Output: [1, 3, 2]
Enter fullscreen mode Exit fullscreen mode
  1. Clear List Contents:
   # Clear list
   my_list = [1, 2, 3, 2]
   my_list.clear()
   print(my_list)  # Output: []
Enter fullscreen mode Exit fullscreen mode
  1. Count Element Occurrences:
   # Count occurrences of an element
   my_list = [1, 2, 3, 2]
   num = my_list.count(2)
   print(num)  # Output: 2
Enter fullscreen mode Exit fullscreen mode
  1. Count Total Elements:

    # Count total elements
    my_list = [1, 2, 3, 2]
    count = len(my_list)
    print(count)  # Output: 4
    

Characteristics of Lists:

  1. Can contain multiple elements (up to (2^{63} - 1) elements).
  2. Can store elements of different types.
  3. Data is stored in an ordered manner.
  4. Allows duplicate data.
  5. Mutable.

List Traversal:

To extract and operate on elements one by one, we use traversal (or iteration).

While Loop:

def list_while_func():
    """
    Function demonstrating list traversal using a while loop.
    """
    my_list = ["python", "java", "c++", "javascript", "go"]
    index = 0
    while index < len(my_list):
        element = my_list[index]
        print(f"List element: {element}")
        index += 1

list_while_func()
Enter fullscreen mode Exit fullscreen mode

For Loop:

def list_for_func():
    """
    Function demonstrating list traversal using a for loop.
    """
    my_list = ["python", "java", "c++", "javascript", "go"]
    for element in my_list:
        print(f"List element: {element}")

list_for_func()
Enter fullscreen mode Exit fullscreen mode

Comparison between while and for loops:

  1. While loops can define conditions and are more flexible. For loops cannot define custom conditions.
  2. While loops can achieve infinite loops; for loops are limited by the container size.
  3. While loops fit any looping scenario, whereas for loops are best for traversing data containers or fixed-iteration loops.

Data Container: Tuple

Tuples are immutable data containers and are defined using parentheses. They can hold mixed types of data.

Basic Syntax:

# Literal
(element1, element2, ..., elementN)

# Variable
variable_name = (element1, element2, ..., elementN)

# Empty tuple
variable_name = ()
variable_name = tuple()
Enter fullscreen mode Exit fullscreen mode

Tuple Indexing:

t = ((1, 2, 3), (4, 5, 6))
print(t[1][2])  # Output: 6
Enter fullscreen mode Exit fullscreen mode

Common Tuple Operations:

  1. index() Method: Return the first occurrence of an element.
  2. count() Method: Count the occurrences of an element.
  3. len() Function: Return the length of the tuple.

Tuple Traversal:

While Loop:

t1 = (1, 2, "Oho", 3, 4, "Oho")
index = 0
while index < len(t1):
    print(f"Tuple element: {t1[index]}")
    index += 1
Enter fullscreen mode Exit fullscreen mode

For Loop:

t2 = (1, 2, "Oho", 3, 4)
for element in t2:
    print(f"Tuple element: {element}")
Enter fullscreen mode Exit fullscreen mode

Note: Tuples cannot be modified, but lists within tuples can have their elements modified.


Data Container: String

Strings are containers for characters. They support indexing but are immutable.

String Indexing:

str1 = "hello"
print(str1[0])  # Output: h
Enter fullscreen mode Exit fullscreen mode

Common String Operations:

  1. Find Substring Index:

    str1 = "hello world"
    index = str1.index("hello")
    print(index)  # Output: 0
    
  2. String Replacement:

    str1 = "hello world"
    new_str1 = str1.replace("h", "H")
    print(new_str1)  # Output: Hello world
    
  3. String Splitting:

    str1 = "Oho Damn Awesome"
    list1 = str1.split(" ")
    print(f"Splitted string: {list1}, type: {type(list1)}")
    
  4. Trim Whitespace:

    str1 = " hello world "
    print(str1.strip())
    
  5. Trim Specific Characters:

    str1 = "12@hello world@21"
    print(str1.strip("12@"))
    
  6. Count Character Occurrences:

    str1 = "hello world"
    count = str1.count("o")
    print(count)  # Output: 2
    
  7. String Length:

    str1 = "hello world"
    count = len(str1)
    print(count)  # Output: 11
    

Characteristics of Strings:

  1. Can only store characters.
  2. Variable length.
  3. Supports indexing.
  4. Allows duplicate characters.
  5. Immutable.
  6. Supports both while and for loops for traversal.

Slicing Sequences

Sequences (lists, tuples, strings) can be sliced to produce a subsequence.

Syntax: sequence[start:end:step]

Examples:

# List slicing
my_list = [0, 1, 2, 3, 4, 5, 7]
result1 = my_list[1:5]
print(result1)  # Output: [1, 2, 3, 4]

# Tuple slicing
my_tuple = (0, 1, 2, 3, 4, 5, 6)
result2 = my_tuple[::-2]
print(result2)  # Output: (6, 4, 2, 0)

# String slicing
str1 = "Over 1 million views, Python enthusiast"
result_str = str1[::-1][9:14]
print(result_str)
Enter fullscreen mode Exit fullscreen mode

Data Container: Set

Sets are containers that do not support duplicate elements and are unordered.

Basic Syntax:

# Literal
{element1, element2, ..., elementN}

# Variable
variable_name = {element1, element2, ..., elementN}

# Empty set
variable_name = set()
Enter fullscreen mode Exit fullscreen mode

Common Set Operations:

  1. Add an Element:

    my_set = {"Damn", "Oho", "Awesome"}
    my_set.add("python")
    print(my_set)
    
  2. Remove an Element:

    my_set = {"Damn", "Oho", "Awesome"}
    my_set.remove("Damn")
    print(my_set)
    
  3. Pop an Element (Randomly):

    my_set = {"Damn", "Oho", "Awesome"}
    pop_set = my_set.pop()
    print(f"Popped element: {pop_set}, Remaining set: {my_set}")
    
  4. Clear the Set:

    my_set = {"Damn", "Oho", "Awesome"}
    my_set.clear()
    print(my_set)
    
  5. Difference of Two Sets:

    my_set1 = {1, 3, 5}
    my_set2 = {1, 4, 6}
    new_set = my_set1.difference(my_set2)
    print(new_set)  # Output: {3, 5}
    
  6. Update Difference (Remove Common Elements):

    my_set1 = {1, 3, 5}
    my_set2 = {1, 4, 6}
    my_set1.difference_update(my_set2)
    print(my_set1)  # Output: {3, 5}
    
  7. Union of Sets:

    my_set1 = {1, 3, 5}
    my_set2 = {1, 4, 6}
    new_set = my_set1.union(my_set2)
    print(new_set)  # Output: {1, 3, 4, 5, 6}
    
  8. Set Length:

    my_set = {1, 2, 3, 4, 5, 6}
    num = len(my_set)
    print(num)  # Output: 6
    

Set Traversal:

# For loop
my_set = {1, 2, 3, 4, 5, 6}
for element in my_set:
    print(f"Set element: {element}")
Enter fullscreen mode Exit fullscreen mode

Data Container: Dictionary

Dictionaries store key-value pairs and are unordered.

Basic Syntax:

# Literal
{key1: value1, key2: value2, ..., keyN: valueN}

# Variable
variable_name = {key1: value1, key2: value2, ..., keyN: valueN}

# Empty dictionary
variable_name = {}
variable_name = dict()
Enter fullscreen mode Exit fullscreen mode

The keys must be unique, and duplicates will overwrite existing values.

Basic Operations:

  1. Accessing Values by Key:

    my_dict = {"John": 99, "Jane": 88, "Jack": 77}
    score = my_dict["John"]
    print(score)  # Output: 99
    
  2. Nested Dictionary:

    grades_dict = {
        "John": {"Math": 77, "Science": 66, "English": 33},
        "Jane": {"Math": 88, "Science": 86, "English": 55},
        "Jack": {"Math": 99, "Science": 96, "English": 66}
    }
    print(f"Student grades: {grades_dict}")
    
  3. Add/Update Elements:

    my_dict = {"John": 99, "Jane": 88, "Jack": 77}
    my_dict["Sam"] = 67
    print(my_dict)  # Output: {'John': 99, 'Jane': 88, 'Jack': 77, 'Sam': 67}
    
    my_dict["Sam"] = 68
    print(my_dict)  # Output: {'John': 99, 'Jane': 88, 'Jack': 77, 'Sam': 68}
    
  4. Delete Elements:

    # Delete elements
    my_dict = {"John": 99, "Jane": 88, "Jack": 77, "Sam": 67}
    score = my_dict.pop("Sam")
    print(f"{my_dict}, Sam's score: {score}")
    
  5. Clear Dictionary:

    my_dict = {"John": 99, "Jane": 88, "Jack": 77, "Sam": 67}
    my_dict.clear()
    print(my_dict)  # Output: {}
    
  6. Get All Keys:

    my_dict = {"John": 99, "Jane": 88, "Jack": 77, "Sam": 67}
    keys = my_dict.keys()
    print(keys)  # Output: dict_keys(['John', 'Jane', 'Jack', 'Sam'])
    
  7. Dictionary Length:

    my_dict = {"John": 99, "Jane": 88, "Jack": 77, "Sam": 67}
    num = len(my_dict)
    print(num)  # Output: 4
    

Dictionary Traversal:

# Dictionary traversal
my_dict = {'John': 99, 'Jane': 88, 'Jack': 77, 'Sam': 67}
for key in my_dict.keys():
    print(f"Key: {key}, Value: {my_dict[key]}")

# Advanced Example
emp_dict = {
    "Jeff": {"Department": "Tech", "Salary": 3000, "Level": 1},
    "Elon": {"Department": "Marketing", "Salary": 5000, "Level": 2},
    "Jack": {"Department": "Marketing", "Salary": 7000, "Level": 4},
    "Sundar": {"Department": "Tech", "Salary": 4000, "Level": 1}
}

for name in emp_dict:
    if emp_dict[name]["Level"] == 1:
        emp_info = emp_dict[name]
        emp_info["Level"] = 2
        emp_info["Salary"] += 1000
        emp_dict[name] = emp_info

print(f"After promotion: {emp_dict}")
Enter fullscreen mode Exit fullscreen mode

General Operations for Data Containers

All data containers support iteration with for loops. Lists, tuples, and strings also support while loops, unlike sets and dictionaries.

In addition to common indexing, containers support type conversion, such as converting to a list, set, etc.

Common Sorting Function:

my_list = [1, 4, 6, 8, 2, 3]
print(f"Sorted list: {sorted(my_list, reverse=True)}")  # Descending order
print(f"Sorted list: {sorted(my_list)}")  # Ascending order
Enter fullscreen mode Exit fullscreen mode

So far, we're halfway through the "Learn Python in 10 Days" series and hope it's been helpful. By the way, check out our team's new Postman alternative EchoAPI. We'd love your feedback! 😊

Best Postman Alternatives for 2024

Top comments (0)