Python lists and list functions
Lists are containers to store a set of values of any data type. F = [ “apple”, “akash”, 7, 7.33, False] Where, “apple” is string, 7 is an integer, 7.33 is a floating point number, and False is a Boolean. We print the list function by using the print() function. We access the list using indexes, like, F[0] will return “apple” and F[3] will return 7.33. Note: We can create al list with items of different types.
List Slicing:
Consider the following list: F = [ “harry”, “tom”, “sam”, “cam”] print (F [0:4]) Op: [ ‘harry’, ‘tom’, ‘sam’]
List methods:
The most important list methods in Python are listed below with illustrations. Consider the following list, L1= [ 1, 8, 7, 2,21,15]
- L1.sort(): updates the list from smaller to larger digits. [1,2,7,8,15,21]
- L1.reverse(): updates the list in reverse order. The new list would be [ 15,21, 2, 7,8, 1]
- L1.append(8): adds 8 at the end of the list.
- L1.insert(3,8): This would add 8 at the 3rd index of the L1 list.
- L1.pop(2): This will delete the element at index 2 and return its value.
- L1.remove(21): This will remove 21 from the list. All these methods or functions make the changes to the original list, L1.
Python Tuples:
Tuple is an immutable data type in Python. It cannot be changed or manipulated. Tuple is created using the parentheses (). Since tuple is an immutable data type, you cannot update or assign the values of the elements inside of the tuple.
Let’s understand tuples with some more examples.
A = (): empty tuple
A = (1,): Tuple with a single element needs a comma
A = (1,7,2): Tuple with more than one element
Once a tuple is defined, its elements cannot be altered or manipulated.
Tuple Methods:
Consider the following tuple. A = (1,7,2)
- A.count(1): It returns the number of times 1 appears in A
- A.index(1): It returns the index of first occurrence of 1 in A