Python Lesson 4
Lesson # 4
Hi All
,
In lesson 3 we start to learn the collection in python. We
finish list. Today we learn more collection types.
Tuples
A tuple is collection which is ordered and unchangeable. It similar
to List but only difference is once you create the tuple you are not able to
change the orders, didn’t add more items, unchangeable.
But yes, there is ways to add items or modify the values in
tuple.
If you need to add value in tuple, you need to create
another tuple and join both.
If you need to modify the tuple value, cast tuple into list,
modify the value and again cast list to tuple.
Example of tuple
MyTuple
= (“Banan”, “Apple”)
In tuple ( ) brackets are used to declare and initialize the
tuple.
You can use count() and index() methods to
search the values in tuple.
Sets
Sets is collection with unordered and unindexed data. It
means there is no index associated with value.
{ } brackets are used to declare and initialize the sets.
To access the sets you need to use for loop because there is
no index associated with sets.
Example
MySet =
{“banana”,”mango”,”apple”}
For x
in MySet:
print(x)
Then you can use if-condition to check the value and do
further operations.
Once you create set you are not able to change the value
because there is no indexing. But you can add new items
For add one value use add() method and for more than
one value use update() method
MySets
= {“banana”}
MySets.add(“new
value 1”)
MySets.update([“new
value 2”,”new value 3”])
Dictionary
After list, dictionary is collection that mostly used by
programmers. Dictionary is collection that’s un-ordered but changeable and
indexed. Dictionary have key paired value.
Example
MyDict
= {
“key1”:”value1”,
“key2”;”value2”
}
To access the items use
Value =
MyDist[“key1”] -> value1
You can change the value by key.
You can use list methods in dictionary as well.
See you in lesson 5 😊
Comments
Post a Comment