I have tried learning how to declare the variable and assign value in python in the first post and then how to write if else in python and in the third post tried hands-on iteration (for loop & while loop) in python.
Now I want to go little further and want to try something where I can hold multiple values in collection form. In variable, we can store single value like this
totalSubjects = 6
But it’s not possible to store multiple values like 80, 90, 76, 88, 91 to totalSubjects. Either I declare multiple variables where maintaining each variable is difficult in a major project or I need collections where I can store multiple values to make this works.
In python, we can store a collection of data in List, Tuple and Dictionary.
I will try List in this blog post.
List: List is another name for the array. In many other languages, they call it an array and in python its list. When I look at List, it’s easy and has so many methods to make operations easy.
Now I am declaring and assigning value to a list in next line
subjects = [‘algebra’, ‘geometry’, ‘biology’, ‘’, physics', 'chemistry'];
marks = [80, 90, 76, 88, 91];
Accessing List elements and assigning a new value is like this
print(subjects) Output: algebra print(marks) Output: 91
Now I wanted to use multiple values from List from 2nd Index to 4th Index,
print(marks[1:4]); Output: [90, 76, 88]
I am replacing/updating value 88 to 99
marks = 99 print(marks[1:4]); Output: [90, 76, 99]
Delete value at specific location from marks List
del marks or marks.remove(88) print(marks) Output: [80, 90, 76, 91]
Concate two List
print(marks+subjects) Output: [80, 90, 76, 88, 91,‘algebra’, ‘geometry’, ‘biology’, ‘’, physics', 'chemistry']
Append value to marks list
marks.append(77) print(marks) Output: [80, 90, 76, 88, 91,,77]
Also published on Medium.