DEV Community

Cover image for Python 102!, Intermediate Concepts
Benjamin Rukundo
Benjamin Rukundo

Posted on

Python 102!, Intermediate Concepts

In our previous discussion about the introduction to python, we last talked about functions, classes and objects.
You can use this link if you want to read about the basic concepts to
Well in this article we are going more intermediate concepts of the python programming language.

Basic Data Structures

Python has support for data structures which enables you to store and access data in your piece of code.

There are several data structures in Python such as:

  • List.
  • Tuple.
  • Set.
  • Dictionary.

1.Lists

A list is a data structure in Python that is a mutable or changeable, ordered sequence of 'items'.- Every element in a list is indexes with umbers. Each element value in a list is called an 'item'. Moreover, a list is ordered, meaning the order of the element matters. There are inbuilt functions in Python which 'change' the list. but more about of that later...

#Empty List
empty_list = []
empty_list = list()

#creating a list
subjects = ['History', 'Math', 'Physics', 'CS']

#printing the list
print(subjects) 
#Prints all the elements of the list
['History', 'Math', 'Physics', 'CS']

#Prints number of elements in list
print(len(subjects))
#output is 4
4

#Prints the 1st element (History)
print(subjects[0])
#output is history
History

#Prints the last element (CS)
print(subjects[-1])
#output is CS
CS

#Prints the 1st & 2nd element (History)
print(subjects[:2])
#displays output of history and math
['History', 'Math']

#Adds the item at the end of the list
subjects.append('DS')
#printed list with the appended item
print(subjects)
['History', 'Math', 'Physics', 'CS', 'DS']

#Adds the item at index 0
subjects.insert(0,'DBMS')
#printed list with the inserted item at the index 0
print(subjects)
['DBMS', 'History', 'Math', 'Physics', 'CS', 'DS']

num_list = [2,6,4,5,3,1]
num_list.sort()
print(num_list)
[1, 2, 3, 4, 5, 6]
print(min(num_list))
print(max(num_list))
print(sum(num_list))
1
6
21

#Prints each item in new line
for item in subjects:
    print(item)
Art
CS
DBMS
DS
Design
History
Physics

#Print the items along with index numbers starting from 0. this is done by enumerate() function
for index,subject in enumerate(subjects):
    print(index,subject)
0 Art
1 CS
2 DBMS
3 DS
4 Design
5 History
6 Physics
Enter fullscreen mode Exit fullscreen mode

2.Tuple:

Doesn't have much supported functions as of list because tuple is immutable

#Empty Tuples
empty_tuple = ()
empty_tuple = tuple()

tup_1 = ('History', 'Math', 'Physics', 'CS')
tup_1[0] = 'Art'
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-25-20f41ff68d0f> in <module>
----> 1 tup_1[0] = 'Art'

TypeError: 'tuple' object does not support item assignment
In [26]:
print(tup_1)
('History', 'Math', 'Physics', 'CS')
Enter fullscreen mode Exit fullscreen mode

3.Sets:

Doesn't care about order & dumps away duplicate item

cs_courses = {'DS','DBMS','History','Math','Physics'}
#Changes order every time the code executes
print('Math' in cs_courses)
#Checks membership in the set
True

art_courses = {'History','Math','Art','Design'}
#Returns common items in both sets
print(cs_courses.intersection(art_courses))
#display output
{'Math', 'History'}

print(cs_courses.difference(art_courses))

#Returns the items not present in second set
{'DS', 'DBMS', 'Physics'}

print(cs_courses.union(art_courses))

#Prints all the items from both sets dropping the duplicate items in a new set
{'Math', 'History', 'Physics', 'DS', 'Design', 'Art', 'DBMS'}

#Empty sets
empty_set = {} #This will create an empty dictionary instead of empty sets
empty_set = set()
Enter fullscreen mode Exit fullscreen mode

4.Dictionary:-

Playing with Key:Value pairs

student = {'name':'harsh', 'age':25, 'course':['Math','Physics']}

#prints dictionary with keys & values
print(student) 
{'name': 'harsh', 'age': 25, 'course': ['Math', 'Physics']}

#Prints values of specified key & gives error on the absence of the key
print(student['name'])
harsh

#Prints values of specified key & doesn't gives error on the absence of the key
print(student.get('phone'))
None


#Let's add a phone no to our dictionary
student['phone'] = '999-9999'

student['name'] = 'akshit'
print(student)
#update a key
{'name': 'akshit', 'age': 25, 'course': ['Math', 'Physics'], 'phone': '999-9999'}

#Updating various keys in a single line of code

student.update({'name':'harsh',
               'age': 21,
               'phone': '111-1111'})
print(student)
{'name': 'harsh', 'age': 21, 'course': ['Math', 'Physics'], 'phone': '111-1111'}
In [48]:
#Prints keys from the dictionary

print(student.keys())
dict_keys(['name', 'age', 'course', 'phone'])

#Prints values from the dictionary
print(student.values())
dict_values(['harsh', 21, ['Math', 'Physics'], '111-1111'])

#Iterates and prints only keys from the dictionary
for key in student:
    print(key)
name
age
course
phone
In [ ]:
#Iterates and prints only keys from the dictionary

for key, in student:
    print(key)
Enter fullscreen mode Exit fullscreen mode

Conclusion

The data structures differ based on mutability and order. Mutability refers to the ability to change an object after its creation. Mutable objects can be modified, added, or deleted after they’ve been created, while immutable objects cannot be modified after their creation. Order, in this context, relates to whether the position of an element can be used to access the element.

Quick Summary

Lists, sets, and tuples are the basic data structures in the Python programming language.
One of the differing points among the data structures is mutability, which is the ability to change an object after its creation.
Lists and tuples are the most useful data types, and they can be found in virtually every Python program.

check out my youtube-video-downloader project on github

Top comments (2)

Collapse
 
hassanbahati profile image
Hassan Bahati

nice

Collapse
 
rukundob451 profile image
Benjamin Rukundo

Thanks bro