Lists and Tuples
Lists and Tuples
Lists:
List Slicing:
List Methods:
2D List:
Tuples:
Tuple Methods:
Practice Questions:
Lists:
A built-in data type that stores set of values
It can store elements of different types (integer, float, string, etc.)
marks = [89.9 , 94.4 , 99.1]
Indexing is allowed in lists.
List Array
Can consist of elements belonging to Only consists of elements belonging to the
different data types same data type
No need to explicitly import a module for Need to explicitly import the array module
the declaration for declaration
Cannot directly handle arithmetic Can directly handle arithmetic operations
operations
Eg:
# str = "hello"
# print(str[0])
# str[0] = "y" not possible
#run it in an IDE
student = ["srikanth" , 18]
print(student[0])
student[0] = "harsh" #posssible
print(student[0])
List Slicing:
Similar to string slicing
List Methods:
list.append(4) adds one element at the end
list.insert(idx, el) insert element at index
list.sort() sorts in ascending order
list.reverse() reverses list
list.sort(reverse=True) sorts in descending order
marks = [2,5,1,7,3]
print(marks.append(9)) #append doesn't return any value
marks.sort()
print(marks)
list = [2, 1, 3, 1]
list.remove(1) removes first occurrence of element [2, 3, 1]
list.pop(idx) removes element at index
2D List:
list1 = [1,2,3,4,5]
list2 = [3,4,5,6,7,8]
list3=[list1,list2]
print(list3)
map():
The map() function is used to apply a given function to every item of an iterable, such as
a list or tuple, and returns a map object (which is an iterator).
Tuples:
A built-in data type that lets us create immutable sequences of values.
tuple_name=(3,4,5,6,7)
Tuple can be accessed in the following way: tuple_name[index_num] .
We cannot assign values to a tuple, tuple_name[0] = 5 is not possible.
tuple_name=(1,) this is a single value tuple and not this tuple_name=(1) here python
interprets 1 as an integer or like any other variable.
Tuple Methods:
tuple_name=(2, 1, 3, 1)
Practice Questions:
WAP to ask the user to enter names of their 3 people & store them in a list.
WAP to check if a list contains a palindrome of elements. (Hint: use copy( ) method).
[1,2,3,2,1] [1, "abc", "abc", 1]
print("Enter a list")
list = []
list.append(input("Value 1:"))
list.append(input("Value 2:"))
list.append(input("Value 3:"))
list.append(input("Value 4:"))
print(list)
rev_list=list.copy()
rev_list.reverse()
if(list==rev_list):
print("The given list is a palindrome")
else:
print("The given list is not a palindrome")