This chapter explores Python lists and dictionaries, covering their properties, operations, and methods for manipulation, along with examples, ensuring a comprehensive understanding of these data structures.
[], separating elements with commas. Examples:
list1 = [2, 4, 6, 8, 10]list2 = ['a', 'e', 'i', 'o', 'u']list3 = [100, 23.5, 'Hello']list4 = [['Physics', 101], ['Chemistry', 202]]list1[0] returns the first element.list1[-1] returns the last element.list1[3] = 'Black'+ operator. It does not modify the original lists:
list1 + list2.* operator:
list1 * 4.in and not in:
'a' in list2 returns True.list1[1:5], list1[::-1] (for reversal).for item in list1:
print(item)
append(x): Adds an element x to the end of the list.extend(iterable): Appends elements from iterable to the list.insert(i, x): Inserts element x at index i.remove(x): Removes the first occurrence of x from the list.pop(i): Removes and returns the element at index i, defaulting to the last item if no index is specified.sort(): Sorts the list in place.reverse(): Reverses the list in place.count(x): Returns the number of occurrences of x in the list.{}. Example:
dict1 = {'Mohan': 95, 'Ram': 89}.dict1['Ram'] returns 89.if 'Mohan' in dict1: to see if the key exists.dict1['Shyam'] = 88dict1['Mohan'] = 100del dict1['Ram']items() to get key-value pairs:for key, value in dict1.items():
print(key, ':', value)
len(): Returns the number of items.keys(): Gets list of keys.values(): Gets list of values.items(): Gets list of key-value pairs.get(key): Returns value for a given key or None.update(dict): Merges another dictionary.