SESSION 5 Lists and Tuples
List:
Python Lists are containers to store a set of values of any data type.
The list can contain different types of elements such as int, float, string, Boolean, etc.
List Indexing
A list can be index just like a string. (For string and string slicing revise previous topic).
List Methods
Consider the following list:
- sort() – updates the list to [1,2,7,8,15,21]
- reverse() – reverse the list to [15,21,2,7,8,1]
- append(11) – adds 11 at the end of the list
- insert(3,0) – This will add 0 at 3 index
- pop(2) – It will delete the element at index 2 and return its value
- remove(21) – It will remove 21 from the last
Tuples in Python:
A tuple is an immutable (can’t change or modified) data type in Python.
Once defined, tuple elements can’t be manipulated or altered.
Tuple methods:
Consider the following tuple,
- count(1) – It will return the number of times 1 occurs in a.
- index(1) – It will return the index of the first occurrence of 1 in a.
Practice Set
- Write a program to store seven fruits in a list entered by the user.
- Write a program to accept the marks of 6 students and display them in a sorted manner.
- Check that a tuple cannot be changed in Python. Calculate its Computational time.
- Write a program to sum a list with 4 numbers.
- Generate list using random module.
- Write a program to count the number of zeros in the following tuple:
Comments
Post a Comment