今日已更新 328 条资讯 | 累计 20300 条内容
关于我们

Python Programming for Beginners – Day 9

augustineowino357-design 2026年06月01日 14:37 4 次阅读 来源:Dev.to

Tuples, Sets, and Dictionaries in Python In the previous lesson, we learned about Lists and how they are used to store multiple items in a single variable. Today, we will learn about three important Python data structures: Tuples Sets Dictionaries These data structures help programmers organize and manage data efficiently in different situations. 1. Tuples in Python A Tuple is a collection of items stored in a single variable. Tuples are: Ordered Unchangeable (Immutable) Allow duplicate values Tuples are created using parentheses "()". Example languages = ( " Python " , " Java " , " C++ " ) print ( languages ) Output ( ' Python ' , ' Java ' , ' C++ ' ) Accessing Tuple Items Tuple items are accessed using indexes. Example languages = ( " Python " , " Java " , " C++ " ) print ( languages [ 0 ]) print ( languages [ 1 ]) Output Python Java Negative Indexing in Tuples Example languages = ( " Python " , " Java " , " C++ " ) print ( languages [ - 1 ]) Output C ++ Tuple Length The "len()" function returns the number of items in a tuple. Example numbers = ( 10 , 20 , 30 ) print ( len ( numbers )) Output 3 Why Tuples are Important Tuples are useful when data should not be modified accidentally. They are commonly used for: Fixed data Coordinates Database records Returning multiple values from functions 2. Sets in Python A Set is a collection of unique items. Sets are: Unordered Unchangeable items Do not allow duplicates Sets are created using curly brackets "{}". Example numbers = { 1 , 2 , 3 , 4 } print ( numbers ) Output {1, 2, 3, 4} Duplicate Values in Sets Sets automatically remove duplicate values. Example numbers = { 1 , 2 , 2 , 3 , 4 } print ( numbers ) Output {1, 2, 3, 4} Adding Items to a Set The "add()" method inserts a new item into a set. Example numbers = { 1 , 2 , 3 } numbers . add ( 4 ) print ( numbers ) Output {1, 2, 3, 4} Removing Items from a Set The "remove()" method removes an item from a set. Example numbers = { 1 , 2 , 3 , 4 } numbers . remove ( 2 ) print

本文内容来源于互联网,版权归原作者所有
查看原文