Humanities/Arts Exam  >  Humanities/Arts Notes  >  Informatics Practices for Class 11  >  Chapter Notes: Working with Lists and Dictionaries

Working with Lists and Dictionaries Chapter Notes | Informatics Practices for Class 11 - Humanities/Arts PDF Download

Introduction to List

  • A list is an ordered sequence that is mutable and can contain one or more elements.
  • Unlike strings, which only contain characters, lists can hold elements of different data types, such as integers, floats, strings, tuples, or even other lists.
  • Lists are useful for grouping elements of mixed data types.
  • Elements in a list are enclosed in square brackets [] and separated by commas.
  • Example: list1 = [2, 4, 6, 8, 10, 12] creates a list of six even numbers, and printing it outputs [2, 4, 6, 8, 10, 12].
  • Example: list2 = ['a', 'e', 'i', 'o', 'u'] creates a list of vowels, and printing it outputs ['a', 'e', 'i', 'o', 'u'].
  • Example: list3 = [100, 23.5, 'Hello'] creates a list with mixed data types, and printing it outputs [100, 23.5, 'Hello'].
  • Example: list4 = [['Physics', 101], ['Chemistry', 202], ['Mathematics', 303]] creates a nested list, and printing it outputs [['Physics', 101], ['Chemistry', 202], ['Mathematics', 303]].

Accessing Elements in a List

  • Each element in a list is accessed using an index, which is a numerical value.
  • The first element has an index of 0, the second has an index of 1, and so on, with indices increasing sequentially.
  • To access an element, use square brackets [] with the index of the element, e.g., list1[0] returns the first element.
  • Negative indices can be used to access elements from the end of the list, where -1 refers to the last element, -2 to the second-to-last, and so on.
  • Example: For list1 = [2, 4, 6, 8, 10, 12], list1[0] returns 2, and list1[3] returns 8.
  • Accessing an index beyond the list’s range results in an IndexError: list index out of range.
  • Example: For list1, list1[15] raises an IndexError.
  • Expressions resulting in an integer index can be used, e.g., list1[1+4] returns 12.
  • Example: list1[-1] returns the last element, 12.
  • The length of a list can be obtained using the len() function, e.g., len(list1) returns 6.
  • The last element can be accessed using list1[len(list1)-1], which returns 12.
  • The first element can be accessed using a negative index based on the length, e.g., list1[-len(list1)] returns 2.

Lists are Mutable

  • Lists in Python are mutable, meaning their contents can be modified after creation.
  • Elements can be changed by assigning a new value to a specific index.
  • Example: For list1 = ['Red', 'Green', 'Blue', 'Orange'], assigning list1[3] = 'Black' changes the fourth element, resulting in ['Red', 'Green', 'Blue', 'Black'].

List Operations

  • Lists support various operations to manipulate their contents.
  • Concatenation: The + operator joins two or more lists.
  • Example: For list1 = [1, 3, 5, 7, 9] and list2 = [2, 4, 6, 8, 10], list1 + list2 returns [1, 3, 5, 7, 9, 2, 4, 6, 8, 10].
  • Example: For list3 = ['Red', 'Green', 'Blue'] and list4 = ['Cyan', 'Magenta', 'Yellow', 'Black'], list3 + list4 returns ['Red', 'Green', 'Blue', 'Cyan', 'Magenta', 'Yellow', 'Black'].
  • Concatenation does not modify the original lists; the result must be assigned to a variable to be stored, e.g., newList = list1 + list2.
  • The + operator requires both operands to be lists; concatenating a list with a non-list type raises a TypeError.

Traversing a List

  • Lists can be traversed to access each element using a for loop or a while loop.
  • Using a for loop: Directly iterate over the elements of the list.
  • Example: For list1 = ['Red', 'Green', 'Blue', 'Yellow', 'Black'], the loop for item in list1: print(item) outputs each color on a new line: Red, Green, Blue, Yellow, Black.
  • Using range() and len(): Iterate over indices to access elements.
  • Example: For the same list1, the loop for i in range(len(list1)): print(list1[i]) produces the same output.
  • The len(list1) function returns the number of elements in the list.
  • The range(n) function generates a sequence of numbers from 0 to n-1.

List Methods and Built-in Functions

  • Python provides several built-in methods and functions for list manipulation.
  • len(): Returns the number of elements in a list. Example: For list1 = [10, 20, 30, 40, 50], len(list1) returns 5.
  • list(): Creates an empty list if no argument is provided, e.g., list1 = list() returns [].
  • list(): Converts a sequence (e.g., string) into a list. Example: For str1 = 'aeiou', list1 = list(str1) returns ['a', 'e', 'i', 'o', 'u'].
  • append(): Adds a single element to the end of the list. Example: For list1 = [10, 20, 30, 40], list1.append(50) results in [10, 20, 30, 40, 50].
  • append(): Can append a list as a single element. Example: list1.append([50, 60]) results in [10, 20, 30, 40, [50, 60]].
  • extend(): Appends each element of a provided list to the end of the list. Example: For list1 = [10, 20, 30] and list2 = [40, 50], list1.extend(list2) results in [10, 20, 30, 40, 50].
  • insert(): Inserts an element at a specified index. Example: For list1 = [10, 20, 30, 40, 50], list1.insert(2, 25) results in [10, 20, 25, 30, 40, 50].
  • count(): Returns the number of occurrences of an element. Example: For list1 = [10, 20, 30, 10, 40, 10], list1.count(10) returns 3.
  • index(): Returns the index of the first occurrence of an element; raises ValueError if not found. Example: For list1 = [10, 20, 30, 20, 40, 10], list1.index(20) returns 1.
  • remove(): Removes the first occurrence of an element; raises ValueError if not found. Example: For list1 = [10, 20, 30, 40, 50, 30], list1.remove(30) results in [10, 20, 40, 50, 30].
  • pop(): Removes and returns the element at the specified index; if no index is provided, removes the last element. Example: For list1 = [10, 20, 30, 40, 50, 60], list1.pop(3) returns 40 and results in [10, 20, 30, 50, 60].
  • reverse(): Reverses the order of elements in the list. Example: For list1 = [34, 66, 12, 89, 28, 99], list1.reverse() results in [99, 28, 89, 12, 66, 34].
  • sort(): Sorts the list in place. Example: For list1 = ['Tiger', 'Zebra', 'Lion', 'Cat', 'Elephant', 'Dog'], list1.sort() results in ['Cat', 'Dog', 'Elephant', 'Lion', 'Tiger', 'Zebra'].
  • sort(reverse=True): Sorts the list in descending order. Example: For list1 = [34, 66, 12, 89, 28, 99], list1.sort(reverse=True) results in [99, 89, 66, 34, 28, 12].
  • sorted(): Returns a new sorted list without modifying the original. Example: For list1 = [23, 45, 11, 67, 85, 56], sorted(list1) returns [11, 23, 45, 56, 67, 85].
  • min(): Returns the smallest element. Example: For list1 = [34, 12, 63, 39, 92, 44], min(list1) returns 12.
  • max(): Returns the largest element. Example: For the same list1, max(list1) returns 92.
  • sum(): Returns the sum of all elements. Example: For the same list1, sum(list1) returns 284.

List Manipulation

  • Lists can be created and manipulated using various methods, such as appending, inserting, modifying, deleting, sorting, and displaying elements.
  • These operations allow for dynamic management of list contents based on user input or program requirements.

Introduction to Dictionaries

  • A dictionary is a mapping data type that associates a set of keys with a set of values.
  • Each key-value pair is called an item, with the key separated from the value by a colon :.
  • Items are unordered, so the order of retrieval may differ from the order of insertion.
  • Items are enclosed in curly braces {} and separated by commas.

Creating a Dictionary

  • Dictionaries are created by enclosing key-value pairs in curly braces {}, with keys and values separated by colons :.
  • Keys must be unique and of an immutable data type (e.g., number, string, tuple).
  • Values can be of any data type and may be repeated.
  • Example: dict1 = {} creates an empty dictionary.
  • Example: dict3 = {'Mohan': 95, 'Ram': 89, 'Suhel': 92, 'Sangeeta': 85} creates a dictionary mapping student names to their marks, and printing it outputs {'Mohan': 95, 'Ram': 89, 'Suhel': 92, 'Sangeeta': 85}.

Accessing Items in a Dictionary

  • Dictionary items are accessed using keys rather than numerical indices.
  • Each key maps to its corresponding value.
  • Example: For dict3 = {'Mohan': 95, 'Ram': 89, 'Suhel': 92, 'Sangeeta': 85}, dict3['Ram'] returns 89.
  • Using a non-existent key raises a KeyError, e.g., dict3['Shyam'] raises KeyError: 'Shyam'.

Membership Operation

  • The in operator checks if a key exists in the dictionary, returning True if present, False otherwise.
  • Example: For dict1 = {'Mohan': 95, 'Ram': 89, 'Suhel': 92, 'Sangeeta': 85}, 'Suhel' in dict1 returns True.
  • The not in operator returns True if the key is not present, False otherwise.
  • Example: For the same dict1, 'Suhel' not in dict1 returns False.

Dictionaries are Mutable

  • Dictionaries are mutable, allowing changes to their contents after creation.
  • Adding a new item: Assign a value to a new key. Example: For dict1 = {'Mohan': 95, 'Ram': 89, 'Suhel': 92, 'Sangeeta': 85}, dict1['Meena'] = 78 results in {'Mohan': 95, 'Ram': 89, 'Suhel': 92, 'Sangeeta': 85, 'Meena': 78}.
  • Modifying an existing item: Overwrite the value of an existing key. Example: For the same dict1, dict1['Suhel'] = 93.5 results in {'Mohan': 95, 'Ram': 89, 'Suhel': 93.5, 'Sangeeta': 85}.

Traversing a Dictionary

  • Dictionaries can be traversed using a for loop to access each key-value pair.
  • Method 1: Iterate over keys and access values using the key. Example: For dict1 = {'Mohan': 95, 'Ram': 89, 'Suhel': 92, 'Sangeeta': 85}, the loop for key in dict1: print(key, ':', dict1[key]) outputs each key-value pair on a new line.
  • Method 2: Use the items() method to iterate over key-value pairs directly. Example: For the same dict1, the loop for key, value in dict1.items(): print(key, ':', value) produces the same output.

Dictionary Methods and Built-in Functions

  • Python provides several methods and functions for dictionary manipulation.
  • len(): Returns the number of key-value pairs. Example: For dict1 = {'Mohan': 95, 'Ram': 89, 'Suhel': 92, 'Sange Morrison': 85}, len(dict1) returns 4.
  • dict(): Creates a dictionary from a sequence of key-value pairs. Example: For pair1 = [('Mohan', 95), ('Ram', 89), ('Suhel', 92), ('Sangeeta', 85)], dict1 = dict(pair1) results in {'Mohan': 95, 'Ram': 89, 'Suhel': 92, 'Sangeeta': 85}.
  • keys(): Returns a list of all keys. Example: For dict1, dict1.keys() returns dict_keys(['Mohan', 'Ram', 'Suhel', 'Sangeeta']).
  • values(): Returns a list of all values. Example: For dict1, dict1.values() returns dict_values([95, 89, 92, 85]).
  • items(): Returns a list of tuples containing key-value pairs. Example: For dict1, dict1.items() returns dict_items([('Mohan', 95), ('Ram', 89), ('Suhel', 92), ('Sangeeta', 85)]).
  • get(): Returns the value for a given key; returns None if the key is not present. Example: For dict1, dict1.get('Sangeeta') returns 85, and dict1.get('Sohan') returns None.
  • update(): Adds key-value pairs from another dictionary. Example: For dict1 = {'Mohan': 95, 'Ram': 89, 'Suhel': 92, 'Sangeeta': 85} and dict2 = {'Sohan': 79, 'Geeta': 89}, dict1.update(dict2) results in {'Mohan': 95, 'Ram': 89, 'Suhel': 92, 'Sangeeta': 85, 'Sohan': 79, 'Geeta': 89}.
  • clear(): Removes all items from the dictionary. Example: For dict1, dict1.clear() results in {}.
  • del: Deletes an item with a specific key or the entire dictionary. Example: For dict1, del dict1['Mohan'] removes the item, and del dict1 deletes the dictionary entirely.

Manipulating Dictionaries

  • Dictionaries can be created and manipulated by adding, modifying, deleting, or retrieving items.
  • Example: Create a dictionary ODD = {1: 'One', 3: 'Three', 5: 'Five', 7: 'Seven', 9: 'Nine'} to map odd numbers to their word representations.
  • Retrieve keys using ODD.keys(), which returns dict_keys([1, 3, 5, 7, 9]).
  • Retrieve values using ODD.values(), which returns dict_values(['One', 'Three', 'Five', 'Seven', 'Nine']).
  • Retrieve items using ODD.items(), which returns dict_items([(1, 'One'), (3, 'Three'), (5, 'Five'), (7, 'Seven'), (9, 'Nine')]).
  • Find the length using len(ODD), which returns 5.
  • Check if a key exists using 7 in ODD, which returns True, or 2 in ODD, which returns False.
  • Retrieve a value using ODD.get(9), which returns 'Nine'.
  • Delete an item using del ODD[9], resulting in {1: 'One', 3: 'Three', 5: 'Five', 7: 'Seven'}.
The document Working with Lists and Dictionaries Chapter Notes | Informatics Practices for Class 11 - Humanities/Arts is a part of the Humanities/Arts Course Informatics Practices for Class 11.
All you need of Humanities/Arts at this link: Humanities/Arts
16 docs

FAQs on Working with Lists and Dictionaries Chapter Notes - Informatics Practices for Class 11 - Humanities/Arts

1. What are lists in Python and how do they differ from other data types?
Ans. Lists in Python are ordered, mutable collections that can hold a variety of data types, including integers, strings, and even other lists. Unlike tuples, which are immutable, lists can be modified after their creation. This makes lists versatile for tasks that require dynamic data manipulation.
2. How can I access elements in a list?
Ans. You can access elements in a list by using their index, which starts at 0. For example, if you have a list called `my_list`, you can access the first element by using `my_list[0]`. You can also use negative indexing to access elements from the end of the list, such as `my_list[-1]` for the last element.
3. What are some common operations I can perform on lists?
Ans. Common operations on lists include adding elements with `append()` or `insert()`, removing elements with `remove()` or `pop()`, and sorting elements with `sort()`. You can also concatenate lists using the `+` operator and repeat lists using the `*` operator.
4. How do I create and access items in a dictionary?
Ans. You can create a dictionary in Python using curly braces `{}` or the `dict()` function. For example, `my_dict = {'key1': 'value1', 'key2': 'value2'}` creates a dictionary. You can access items using their keys, like `my_dict['key1']`, which would return 'value1'.
5. What is the membership operation in dictionaries and how does it work?
Ans. The membership operation in dictionaries checks if a key exists in the dictionary using the `in` keyword. For example, `if 'key1' in my_dict:` will evaluate to `True` if 'key1' is a key in `my_dict`, allowing for easy verification of key existence.
Related Searches

Exam

,

Viva Questions

,

Sample Paper

,

Extra Questions

,

Summary

,

Free

,

Previous Year Questions with Solutions

,

Working with Lists and Dictionaries Chapter Notes | Informatics Practices for Class 11 - Humanities/Arts

,

Working with Lists and Dictionaries Chapter Notes | Informatics Practices for Class 11 - Humanities/Arts

,

shortcuts and tricks

,

study material

,

Semester Notes

,

video lectures

,

practice quizzes

,

Objective type Questions

,

Important questions

,

pdf

,

MCQs

,

ppt

,

Working with Lists and Dictionaries Chapter Notes | Informatics Practices for Class 11 - Humanities/Arts

,

mock tests for examination

,

past year papers

;