Movatterモバイル変換


[0]ホーム

URL:


Skip to content
DEV Community
Log in Create account

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 variablevariable_name=[Element1,Element2,Element3,...]# Define an empty listvariable_name=[]variable_name=list()
Enter fullscreen modeExit fullscreen mode

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

# Listlanguages=['python','c','c++','java']print(languages)print(type(languages))# Nested listnested_list=[[1,2,"damn it"],[4,5,True]]print(nested_list)print(type(nested_list))
Enter fullscreen modeExit 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 indexingnames=["tom","jack","alex"]print(names[0])# Output: tomprint(names[1])# Output: jackprint(names[2])# Output: alex
Enter fullscreen modeExit fullscreen mode

Reverse indexing is also supported:

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

For nested lists:

# Nested list indexingnested_list=[[1,2,"damn it"],[4,5,True]]print(nested_list[1][2])# Output: Trueprint(nested_list[0][2])# Output: damn it
Enter fullscreen modeExit 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 aValueError.
# Query indexlanguages=['python','c','c++','java']index=languages.index("python")print(f"Index of'python':{index}")
Enter fullscreen modeExit fullscreen mode
  1. Modify Elements:Modify the value at a specific index.
# Modify elementsmy_list=[1,2,3,4]my_list[0]=8print(my_list)my_list[-1]=6print(my_list)
Enter fullscreen modeExit fullscreen mode
  1. Insert Elements:
# Insert elementsmy_list=[1,2,3,4]my_list.insert(2,'damn it')print(my_list)
Enter fullscreen modeExit fullscreen mode
  1. Append Elements:
# Append elementsmy_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 modeExit fullscreen mode
  1. Extend a List:
# Extend a listmy_list=[1,2,3,4]my_list.extend([4,5,6])print(my_list)# Output: [1, 2, 3, 4, 4, 5, 6]
Enter fullscreen modeExit fullscreen mode
  1. Delete Elements:
# Delete elementsmy_list=[1,2,3,4]delmy_list[0]print(my_list)# Output: [2, 3, 4]my_list.pop(0)print(my_list)# Output: [3, 4]
Enter fullscreen modeExit fullscreen mode
  1. Remove a Specific Element:
# Remove a specific elementmy_list=[1,2,3,2]my_list.remove(2)print(my_list)# Output: [1, 3, 2]
Enter fullscreen modeExit fullscreen mode
  1. Clear List Contents:
# Clear listmy_list=[1,2,3,2]my_list.clear()print(my_list)# Output: []
Enter fullscreen modeExit fullscreen mode
  1. Count Element Occurrences:
# Count occurrences of an elementmy_list=[1,2,3,2]num=my_list.count(2)print(num)# Output: 2
Enter fullscreen modeExit fullscreen mode
  1. Count Total Elements:

    # Count total elementsmy_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:

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

For Loop:

deflist_for_func():"""    Function demonstrating list traversal using a for loop."""my_list=["python","java","c++","javascript","go"]forelementinmy_list:print(f"List element:{element}")list_for_func()
Enter fullscreen modeExit 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)# Variablevariable_name=(element1,element2,...,elementN)# Empty tuplevariable_name=()variable_name=tuple()
Enter fullscreen modeExit fullscreen mode

Tuple Indexing:

t=((1,2,3),(4,5,6))print(t[1][2])# Output: 6
Enter fullscreen modeExit 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=0whileindex<len(t1):print(f"Tuple element:{t1[index]}")index+=1
Enter fullscreen modeExit fullscreen mode

For Loop:

t2=(1,2,"Oho",3,4)forelementint2:print(f"Tuple element:{element}")
Enter fullscreen modeExit 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 modeExit 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 slicingmy_list=[0,1,2,3,4,5,7]result1=my_list[1:5]print(result1)# Output: [1, 2, 3, 4]# Tuple slicingmy_tuple=(0,1,2,3,4,5,6)result2=my_tuple[::-2]print(result2)# Output: (6, 4, 2, 0)# String slicingstr1="Over 1 million views, Python enthusiast"result_str=str1[::-1][9:14]print(result_str)
Enter fullscreen modeExit fullscreen mode

Data Container: Set

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

Basic Syntax:

# Literal{element1,element2,...,elementN}# Variablevariable_name={element1,element2,...,elementN}# Empty setvariable_name=set()
Enter fullscreen modeExit 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 loopmy_set={1,2,3,4,5,6}forelementinmy_set:print(f"Set element:{element}")
Enter fullscreen modeExit fullscreen mode

Data Container: Dictionary

Dictionaries store key-value pairs and are unordered.

Basic Syntax:

# Literal{key1:value1,key2:value2,...,keyN:valueN}# Variablevariable_name={key1:value1,key2:value2,...,keyN:valueN}# Empty dictionaryvariable_name={}variable_name=dict()
Enter fullscreen modeExit 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"]=67print(my_dict)# Output: {'John': 99, 'Jane': 88, 'Jack': 77, 'Sam': 67}my_dict["Sam"]=68print(my_dict)# Output: {'John': 99, 'Jane': 88, 'Jack': 77, 'Sam': 68}
  4. Delete Elements:

    # Delete elementsmy_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 traversalmy_dict={'John':99,'Jane':88,'Jack':77,'Sam':67}forkeyinmy_dict.keys():print(f"Key:{key}, Value:{my_dict[key]}")# Advanced Exampleemp_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}}fornameinemp_dict:ifemp_dict[name]["Level"]==1:emp_info=emp_dict[name]emp_info["Level"]=2emp_info["Salary"]+=1000emp_dict[name]=emp_infoprint(f"After promotion:{emp_dict}")
Enter fullscreen modeExit fullscreen mode

General Operations for Data Containers

All data containers support iteration withfor loops. Lists, tuples, and strings also supportwhile 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 orderprint(f"Sorted list:{sorted(my_list)}")# Ascending order
Enter fullscreen modeExit 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 alternativeEchoAPI. We'd love your feedback! 😊

Best Postman Alternatives for 2024

Top comments(0)

Subscribe
pic
Create template

Templates let you quickly answer FAQs or store snippets for re-use.

Dismiss

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment'spermalink.

For further actions, you may consider blocking this person and/orreporting abuse

  • Location
    Brooklyn, NY
  • Joined

More fromWilliam

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Log in Create account

[8]ページ先頭

©2009-2025 Movatter.jp