Class notes: 2/26/2021
Python Collections:
- When we want to treat some data as a group, then it is not good to store the data in individual variables.
- We need to use a collection to store the data a a group
- For eg, An university offers different courses to her students. So, all the courses should be stored as a group in a collection.
Note: list is mutable which allows us to change its contents.
Say in restaurant, they can remove one item from their one item.
say, fish is not available, they can remove from menu for short time and
they may add some non-veg item. so this way contents can be changed.
- In python, we have following collection types
list
tuple
set
frozenset
dict
List
* List can be used to store the group of elements in a sequence.
* a list can store both homogeneous and hetrogeneous elements
what is that mean?
-> homegeneour -> same type
-> hetrogeneous -> different type
* A list is represented with [] (square braces)
within square braces, we can seperate elements with comma ,
* list is a mutable object.
* a list can store duplicate elements
* each element in a list has a positive & negative index.
important points
sequance
mutable
duplicate
For eg
phone_numbers=[1234,2345, 3423,2123]
these are list of phone numbers. list of homogenous elements because these are all integers.
airlines=["AI",10,"JA",6]
if you look at this, there are two strings and two integers.
so, this is a list of hetrogeneous. because elements are not of same types.
You can have float value as well.
We can also create empty list as well. For eg,
sample=[ ] # empty list
lst1=[ ]
lst2=[10,'x',20.15,True]
we have list containing 4 elements
This is list with known size and known elements.
Lets look at another eg
lst3=[None]*5
none is unknown but list will create element with 5 elements but we don't know. We will append later
we create a list with 5 element with known size and unknow elements
length of a list:
airlines=["AI","JA","LT", "VA"]
print(len(airlines))
output: 4
the output is the length of elements
courses=['Python', 'Data Science', 'Big Data']
index 0 1 2
negative index -3 -2 -1
for last element, so do not use comma
print(courses[1]) => output is Data Science
print(courses[3]) => output is an "error"
because list has 3 items with index 0, 1, and 2.
print(Courses[-3]) => output? its python
because negative index starts with -1.
No comments:
Post a Comment