List, Tuple, Set, Dictionary-7
List, Tuple, Set, Dictionary-7
List
● A list is a collection of different kinds of values or items.
● Python lists are mutable i.e. we can change their elements after forming.
● [ ] are used to enclose the list items
● The comma (,) serve as separators.
● The lists items are in order.
● The list element can be accessed via the index.
List operations
-1 refers to the last item, -2 refers to the second last item etc
List Index
● Return the third, fourth, and fifth item:
thislist = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]
print(thislist[2:5])
● By leaving out the start value, the range will start at the first item:
thislist = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]
print(thislist[:4])
● By leaving out the end value, the range will go on to the end of the list:
thislist = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]
print(thislist[2:])
Adding element to the list : append()
1. l=[]
2. n = int(input("Enter the number of elements in the list:"))
3. # for loop to take the input
4. for i in range(0,n):
5. l.append(input("Enter the item:"))
6. print("printing the list items..")
7.
10. for i in l:
11. print(i, end = " ")
remove() : removing the lament from the list
1. list = [0,1,2,3,4]
2. print("printing original list: ");
3. for i in list:
4. print(i,end=" ")
5. list.remove(2)
6. print("\nprinting the list after the removal of first element...")
7. for i in list:
8. print(i,end=" ")
Len () , max() , min()
1. list1 = [12, 16, 18, 20, 39, 40]
2. # finding length of the list
3. len(list1)
4.
Sqaress = [ ]
For x in range (1,11);
squares.append(x**2)
Print squares
List comprehension
sorted(tp , reverse = true) : sort the elements based on value passed to reverse
parameter
Dictionary
● Represents group of elements arranged in key value : pair
● Key : value is inserted using { }
● Duplicate keys are not allowed
● Keys are immutable
D = dict(z)