
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()
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))
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
Reverse indexing is also supported:
names=["tom","jack","alex"]print(names[-3])# Output: tomprint(names[-2])# Output: jackprint(names[-1])# Output: alex
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
Note: Do not try to access indexes out of range; it will cause an IndexError.
Common List Operations:
- Insert an element
- Delete an element
- Clear elements
- Modify elements
- Count elements
These operations are referred to as methods of the list.
- List Query Functionality:Find the index of a specified element. If not found, it raises a
ValueError
.
# Query indexlanguages=['python','c','c++','java']index=languages.index("python")print(f"Index of'python':{index}")
- 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)
- Insert Elements:
# Insert elementsmy_list=[1,2,3,4]my_list.insert(2,'damn it')print(my_list)
- 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]]
- 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]
- 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]
- Remove a Specific Element:
# Remove a specific elementmy_list=[1,2,3,2]my_list.remove(2)print(my_list)# Output: [1, 3, 2]
- Clear List Contents:
# Clear listmy_list=[1,2,3,2]my_list.clear()print(my_list)# Output: []
- Count Element Occurrences:
# Count occurrences of an elementmy_list=[1,2,3,2]num=my_list.count(2)print(num)# Output: 2
Count Total Elements:
# Count total elementsmy_list=[1,2,3,2]count=len(my_list)print(count)# Output: 4
Characteristics of Lists:
- Can contain multiple elements (up to (2^{63} - 1) elements).
- Can store elements of different types.
- Data is stored in an ordered manner.
- Allows duplicate data.
- 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()
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()
Comparison between while and for loops:
- While loops can define conditions and are more flexible. For loops cannot define custom conditions.
- While loops can achieve infinite loops; for loops are limited by the container size.
- 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()
Tuple Indexing:
t=((1,2,3),(4,5,6))print(t[1][2])# Output: 6
Common Tuple Operations:
- index() Method: Return the first occurrence of an element.
- count() Method: Count the occurrences of an element.
- 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
For Loop:
t2=(1,2,"Oho",3,4)forelementint2:print(f"Tuple element:{element}")
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
Common String Operations:
Find Substring Index:
str1="hello world"index=str1.index("hello")print(index)# Output: 0
String Replacement:
str1="hello world"new_str1=str1.replace("h","H")print(new_str1)# Output: Hello world
String Splitting:
str1="Oho Damn Awesome"list1=str1.split("")print(f"Splitted string:{list1}, type:{type(list1)}")
Trim Whitespace:
str1=" hello world"print(str1.strip())
Trim Specific Characters:
str1="12@hello world@21"print(str1.strip("12@"))
Count Character Occurrences:
str1="hello world"count=str1.count("o")print(count)# Output: 2
String Length:
str1="hello world"count=len(str1)print(count)# Output: 11
Characteristics of Strings:
- Can only store characters.
- Variable length.
- Supports indexing.
- Allows duplicate characters.
- Immutable.
- 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)
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()
Common Set Operations:
Add an Element:
my_set={"Damn","Oho","Awesome"}my_set.add("python")print(my_set)
Remove an Element:
my_set={"Damn","Oho","Awesome"}my_set.remove("Damn")print(my_set)
Pop an Element (Randomly):
my_set={"Damn","Oho","Awesome"}pop_set=my_set.pop()print(f"Popped element:{pop_set}, Remaining set:{my_set}")
Clear the Set:
my_set={"Damn","Oho","Awesome"}my_set.clear()print(my_set)
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}
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}
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}
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}")
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()
The keys must be unique, and duplicates will overwrite existing values.
Basic Operations:
Accessing Values by Key:
my_dict={"John":99,"Jane":88,"Jack":77}score=my_dict["John"]print(score)# Output: 99
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}")
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}
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}")
Clear Dictionary:
my_dict={"John":99,"Jane":88,"Jack":77,"Sam":67}my_dict.clear()print(my_dict)# Output: {}
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'])
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}")
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
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! 😊
Top comments(0)
For further actions, you may consider blocking this person and/orreporting abuse