Lists, Tuples, Sets and Dictionary
Chapter 9 · Tamil Nadu State Board
- 22 min read
- 5-question quiz
Every key point below shows the sentence from your textbook it comes from. Book back answers are solved and checked against the book; answers we could not prove are left out. How we check content
In short
This lesson explains how Python collections store and organise groups of values. It teaches how to create, access, change and remove elements in lists, tuples, sets and dictionaries. It also shows how loops and collection functions help process values, and how set operations compare collections. These skills help students write programs that manage and work with data.
Written by AI from this lesson. How we check it
Key points
- Lists are ordered collections that can hold different kinds of values, and their elements can be changed.
From your textbook
“It is an ordered collection of values enclosed within square brackets [ ].”
- List elements can be located using positive or negative index numbers.
From your textbook
“index value is an integer number which can be positive or negative.”
- Lists can be changed by assigning new values, and elements can be added or deleted with suitable operations.
From your textbook
“The elements can be modified or mutable which means the elements can be replaced, added or removed.”
- Tuples resemble lists but cannot have their values changed after creation.
From your textbook
“The elements of a list are changeable (mutable) whereas the elements of a tuple are unchangeable (immutable)”
- Sets are mutable collections that have no fixed order and do not keep duplicate elements.
From your textbook
“A Set is a mutable and an unordered collection of elements without duplicates.”
- Set operations can combine sets, find common members, or identify elements that differ between them.
From your textbook
“set operations such as Union, Intersection, difference and Symmetric difference.”
- Dictionaries associate keys with values, and a key is used to access its paired value.
From your textbook
“the dictionary type stores a key along with its element.”
Formulas in this chapter
- List creationVariable = [element-1, element-2, element-3 …… element-n]Explained here
- Accessing one elementprint (List_Variable[index of a element])Explained here
- List for loopfor index_var in list: print (index_var)Explained here
- Change one list elementList_Variable[index of an element] = Value to be changedExplained here
- Change a range of list elementsList_Variable[index from : index to] = Values to changedExplained here
- Insert an elementList.insert(position index, element)Explained here
- List comprehension formList = [ expression for variable in range ]Explained here
- Dictionary syntaxDictionary_Name = {Key_1: Value_1, Key_2: Value_2, ..., Key_n: Value_n}Explained here
- Dictionary comprehensionDict = {expression for variable in sequence [if condition]}Explained here
Python Lists and Their Features
A list is an ordered collection of values written inside square brackets [ ]. Each value is an element, and elements are indexed from zero. A list can contain numbers, characters, strings, or even another list.
Definition
- Mutable
- A list is mutable because its elements can be replaced, added, or removed.
Definition
- Nested list
- A nested list is a list that contains another list as one of its elements.
Examples of lists
- Marks = [10, 23, 41, 75] contains integer elements.
- Fruits = [“Apple”, “Orange”, “Mango”, “Banana”] contains string elements.
- MyList = [ ] is an empty list.
- Mylist = [ “Welcome”, 3.14, 10, [2, 4, 6] ] contains different types of elements and a nested list.
Creating and Accessing List Elements
Create a list by placing its elements inside square brackets. Use the list name and an index inside square brackets to access one element. Positive indexes count from the beginning, while negative indexes count backward from the end.
Variable = [element-1, element-2, element-3 …… element-n]
Variable is the list name, and each element is a value stored in the list.
print (List_Variable[index of a element])
List_Variable is the list name, and the index identifies the element to print.
Positive and negative indexes for Marks = [10, 23, 41, 75]
| Positive index | Negative index |
|---|---|
| 0 refers to 10 | -4 refers to 10 |
| 1 refers to 23 | -3 refers to 23 |
| 2 refers to 41 | -2 refers to 41 |
| 3 refers to 75 | -1 refers to 75 |
For Marks = [10, 23, 41, 75], print (Marks[0]) prints 10. A negative index can access an element from the end; print (Marks[-1]) accesses the last element.
Reading List Elements with Loops
A while loop can read list elements by starting with index zero and increasing the index each time. The condition must stop the loop after the last element. Using len() for the limit lets the loop match the list's number of elements.
Worked example
Display all elements of Marks = [10, 23, 41, 75] using a while loop.
Try it first, then show the solutionSolution
- Set i = 0, the first index.
- Repeat while i < 4.
- Print Marks[i], then increase i by 1.
Answer: The output is 10, 23, 41, 75, in that order.
Reverse indexing starts at -1 for the last element, then moves backward through -2, -3, and so on. In the given reverse loop, i begins at -1 and decreases by 1 each time.
Worked example
Read Marks = [10, 23, 41, 75] in reverse order using negative indexes.
Try it first, then show the solutionSolution
- Set i = -1.
- Repeat while i >= -4.
- Print Marks[i], then set i = i + -1.
Answer: The output is 75, 41, 23, 10, in that order.
Definition
- len()
- The len() function returns the number of elements in a list.
If a list contains another list as an element, len() counts that inner list as one element. The len() function can also set the upper limit when a loop reads a list.
Worked example
Display every element of MySubject = ["Tamil", "English", "Comp. Science", "Maths"] using len() in a while loop.
Try it first, then show the solutionSolution
- Set i = 0.
- Repeat while i < len(MySubject).
- Print MySubject[i], then increase i by 1.
Answer: The output is Tamil, English, Comp. Science, Maths, in that order.
Using a for Loop with a List
A for loop reads each element of a list one by one. The loop variable represents the current element, and the print statement displays it.
for index_var in list: print (index_var)
index_var represents each element in turn, and list is the list being read.
Worked example
Print every element of Marks = [23, 45, 67, 78, 98] using a for loop.
Try it first, then show the solutionSolution
- Take each element of Marks in turn as x.
- Print x.
Answer: The output is 23, 45, 67, 78, 98, in that order.
Remember: List indexes start at zero. Use negative indexes to count backward from the last element.
Changing Elements in a Python List
Python lists are mutable, so their elements can be changed. Use the assignment operator = to replace one element or a range of elements. In a range, the ending index is excluded.
List_Variable[index of an element] = Value to be changed
The index identifies the element to replace, and the value on the right becomes the new element.
List_Variable[index from : index to] = Values to changed
index from begins the range. index to is excluded, so [0:5] covers indexes 0 to 4.
Worked example
Change the value at index 2 in MyList = [2, 4, 5, 8, 10].
Try it first, then show the solutionSolution
- Use MyList[2] = 6.
- The element 5 is replaced by 6.
Answer: [2, 4, 6, 8, 10]
Worked example
Change all values in MyList = [1, 3, 5, 7, 9] using MyList[0:5] = 2,4,6,8,10.
Try it first, then show the solutionSolution
- The range [0:5] includes indexes 0 to 4.
- Replace those elements with 2, 4, 6, 8, 10.
Answer: [2, 4, 6, 8, 10]
Remember: The ending index in a list range is not included.
Adding and Inserting List Elements
append() and extend()
| append() | extend() |
|---|---|
| Adds one element to the end of a list. | Adds more than one element to an existing list. |
| Example: Mylist.append(90) | Example: Mylist.extend([71, 32, 29]) |
For extend(), put the multiple elements inside square brackets. Both append() and extend() add elements at the end of the list.
Definition
- insert()
- insert() adds an element at a chosen position in a list.
List.insert(position index, element)
position index gives where the new element goes, and element is the value to insert.
Worked example
Insert 'Ramakrishnan' into MyList at index 3.
Try it first, then show the solutionSolution
- Use MyList.insert(3, 'Ramakrishnan').
- The new element goes in the 4th position.
- Existing elements from that position shift one place to the right.
Answer: [34, 98, 47, 'Ramakrishnan', 'Kannan', 'Gowrisankar', 'Lenin', 'Sreenivasan']
Deleting Elements from a Python List
Ways to delete list elements
| Method | What it does |
|---|---|
| del List[index] | Deletes an element when its index is known. |
| del List[index from : index to] | Deletes a range of elements; the ending index is excluded. |
| del List | Deletes the entire list. |
| List.remove(element) | Deletes a specified element when you do not know its index. |
| List.pop(index of an element) | Deletes and returns the element at the given index. Without an index, it deletes and returns the last element. |
| List.clear() | Deletes all elements but keeps the list. |
del can delete one element, a range, or the entire list. With remove(), specify the element to delete. With pop(), specify an index if needed; it deletes only one element.
Worked example
Delete the element at index 1 from MySubjects = ['Tamil', 'Hindi', 'Telugu', 'Maths'].
Try it first, then show the solutionSolution
- Use del MySubjects[1].
- The element 'Hindi' is removed.
Answer: ['Tamil', 'Telugu', 'Maths']
Worked example
Delete MySubjects[1:3] from ['Tamil', 'Hindi', 'Telugu', 'Maths'].
Try it first, then show the solutionSolution
- The range starts at index 1 and ends before index 3.
- The elements 'Hindi' and 'Telugu' are deleted.
Answer: ['Tamil', 'Maths']
Worked example
Remove 89 from MyList = [12, 89, 34, 'Kannan', 'Gowrisankar', 'Lenin'].
Try it first, then show the solutionSolution
- Use MyList.remove(89).
- The element 89 is removed.
Answer: [12, 34, 'Kannan', 'Gowrisankar', 'Lenin']
Worked example
Use MyList.pop(1) on [12, 89, 34, 'Kannan', 'Gowrisankar', 'Lenin'].
Try it first, then show the solutionSolution
- Index 1 contains 89.
- pop(1) deletes that element and returns it.
Answer: Returned value: 89; remaining list: [12, 34, 'Kannan', 'Gowrisankar', 'Lenin']
Remember: del List removes the list itself, while List.clear() removes its elements and keeps the list.
Using range() to Generate Values
The range() function generates a series of values. Its form is range(start value, end value, step value). The end value is not included, so the series stops at end value − 1.
The three range() arguments
- start value: where the series begins; zero is the default.
- end value: the upper limit, which is not included.
- step value: an optional interval between values.
Worked example
Generate whole numbers up to 10 with for x in range (1, 11): print(x).
Try it first, then show the solutionSolution
- The series begins at 1.
- The end value 11 is excluded.
Answer: 1 2 3 4 5 6 7 8 9 10
Worked example
Generate the first 10 even numbers with for x in range (2, 11, 2): print(x).
Try it first, then show the solutionSolution
- Start at 2 and increase by 2 each time.
- Stop before reaching the end value 11.
Answer: 2 4 6 8 10
Creating Lists with range() and List Comprehensions
Use list() to turn the values from range() into a list. For example, Even_List = list(range(2,11,2)) creates [2, 4, 6, 8, 10]. A loop can also build a list by adding each new value with append().
Worked example
Create a list of squares of the first 10 natural numbers using a loop.
Try it first, then show the solutionSolution
- Start with an empty list named squares.
- Use range(1,11) to get values from 1 through 10.
- For each x, calculate x ** 2 and append the result to squares.
Answer: [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
Definition
- List comprehension
- A short way to create a list of values that satisfy a condition or come from an expression.
List = [ expression for variable in range ]
The expression is evaluated for each variable value generated by range.
Worked example
Generate squares of the first 10 natural numbers using list comprehension: squares = [ x ** 2 for x in range(1,11) ].
Try it first, then show the solutionSolution
- range(1,11) supplies values from 1 through 10.
- For each value, x ** 2 is calculated and placed in the list.
Answer: [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
Important List Functions
List functions and what they do
| Function | Purpose |
|---|---|
| copy() | Returns a copy of the list. |
| count(value) | Returns the number of times the value occurs in the list. |
| index(element) | Returns the index of the first matching element. |
| reverse() | Reverses the order of elements in the list. |
| sort() | Sorts the elements in the list. Ascending order is the default. |
| max(list) | Returns the maximum value in a list. |
| min(list) | Returns the minimum value in a list. |
| sum(list) | Returns the sum of values in a list. |
In sort(), reverse=True sorts in descending order. The optional key argument can name a user-defined function that sets the sorting criteria. sort() changes the original list.
Examples of list function results
- MyList=[12, 12, 36]; MyList.copy() gives [12, 12, 36].
- MyList=[36 ,12 ,12]; MyList.count(12) gives 2.
- MyList=[36 ,12 ,12]; MyList.index(12) gives 1.
- MyList=[36 ,23 ,12]; MyList.reverse() gives [12 ,23 ,36].
- For MyList=[21,76,98,23], max(MyList) is 98, min(MyList) is 21, and sum(MyList) is 218.
Remember: Remember: sort() changes the original list, and ascending order is the default.
List Programs and Their Results
What the programs demonstrate
- Find numbers divisible by 4 in the range from 1 to 20: [0, 4, 8, 12, 16, 20].
- Check whether an entered country is in a list: India is found in the given list, while Japan is not.
- Read marks for six subjects, display each mark, and calculate the total: 308 for the shown inputs.
- Read prices for 5 items and display their sum, product, and average: Rs. 75, Rs. 375000, and Rs. 15.0.
- Calculate annual salaries by multiplying monthly salaries by 12. In the shown example, 2 Employees out of 5 employees meet the program's salary condition.
- Create a list from 1 to 10 and delete its even numbers: [1, 3, 5, 7, 9].
- Generate Fibonacci values in a list and find their sum. For 10 terms, the list is [0, 1, 1, 2, 3, 5, 8, 13, 21, 34] and the sum is 88.
Tuple Basics and List Comparison
Definition
- Tuple
- A tuple is a collection whose elements cannot be changed after it is created.
Tuples and lists
| List | Tuple |
|---|---|
| Elements can be changed (mutable). | Elements cannot be changed (immutable). |
| Elements are enclosed in square brackets. | Elements are usually enclosed in parentheses, but parentheses can be left out. |
| Iterating is slower than iterating a tuple. | Iterating is faster than iterating a list. |
A tuple may contain any number of elements, including no elements. A tuple with one element needs a comma after that element. Without the comma, Python treats the value as an ordinary data type.
Ways to create a tuple
- Empty tuple: Tuple_Name = ( )
- Tuple with elements: Tuple_Name = (E1, E2, E2 ……. En)
- Tuple without parentheses: Tuple_Name = E1, E2, E3 ….. En
- Create a tuple from a list: Tuple_Name = tuple( [list elements] )
Worked example
How do you create a tuple with one element?
Try it first, then show the solutionSolution
- MyTup4 = (10) creates an integer, not a tuple.
- MyTup5 = (10,) includes the comma needed for a single-element tuple.
Answer: MyTup5 is a tuple. A one-element tuple is also called a “Singleton” tuple.
Accessing, Joining, and Deleting Tuples
Each tuple element has an index number, starting from zero. Use an index or a slice to access selected elements. A tuple’s elements cannot be changed, but two tuples can be joined, and an entire tuple can be deleted.
Tuple access examples
- Tup1[2:5] accesses elements at indices 2 through 4.
- Tup1[:5] accesses elements from the beginning up to index 4.
- Tup1[4:] accesses elements from index 4 through the end.
- Tup1[:] accesses all elements.
Worked example
What is printed when Tup1 = (2,4,6,8,10), Tup2 = (1,3,5,7,9), and Tup3 = Tup1 + Tup2?
Try it first, then show the solutionSolution
- The + operator joins the elements of Tup1 and Tup2.
Answer: (2, 4, 6, 8, 10, 1, 3, 5, 7, 9)
Use del tuple_name to delete an entire tuple. Printing that tuple after deletion causes Python to show an error because the name is no longer defined.
Remember: Tuple elements are immutable: you can join tuples or delete a whole tuple, but you cannot change an element.
Tuple Assignment and Returning Multiple Values
Definition
- Tuple assignment
- Tuple assignment gives values on the right side of the assignment operator to their matching variables on the left side.
The values on the right are evaluated before assignment. The number of values on both sides must match; otherwise, Python generates an error.
Worked example
What values are assigned by (a, b, c) = (34, 90, 76)?
Try it first, then show the solutionSolution
- Match each value on the right with the variable in the same position on the left.
Answer: a = 34, b = 90, c = 76.
A function can return multiple values together as a tuple. For example, Min_Max(n) returns the maximum and minimum values from n. They can be assigned to separate variables: (Max_Num, Min_Num) = Min_Max(Num).
Worked example
What does Min_Max return for Num = (12, 65, 84, 1, 18, 85, 99)?
Try it first, then show the solutionSolution
- The function sets a = max(n) and b = min(n).
- It returns (a, b), so the maximum is assigned to Max_Num and the minimum to Min_Num.
Answer: Maximum value = 99; Minimum value = 1.
Nested Tuples and Tuple Programs
Definition
- Nested tuple
- A nested tuple is a tuple defined inside another tuple, and each inner tuple is treated as one element.
A for loop can visit each inner tuple. Some functions used with lists can also be used with tuples.
Worked example
How can a program swap two values using tuple assignment?
Try it first, then show the solutionSolution
- Start with values a and b.
- Assign (a, b) = (b, a).
Answer: The values are exchanged. In the given example, 54 and 38 become 38 and 54.
Worked example
What does the Circle(r) function return when pi = 3.14 and the radius is 5?
Try it first, then show the solutionSolution
- The function returns (pi*r*r, 2*pi*r).
- The first value is the area and the second is the circumference.
Answer: Area of the circle = 78.5; Circumference of the circle = 31.400000000000002.
Worked example
What tuple is made from Numbers = (5, -8, 6, 8, -4, 3, 1) when only positive numbers are added?
Try it first, then show the solutionSolution
- Check each number and add it to Positive only if i > 0.
Answer: Positive Numbers: (5, 6, 8, 3, 1)
Creating Sets in Python
A set stores elements inside curly brackets, separated by commas. You can also create a set with the set() function. A set keeps only one copy of each value, even if a value is written more than once.
Worked example
Create a set from a list.
Try it first, then show the solutionSolution
- Create the list: MyList=[2,4,6,8,10]
- Pass the list to set(): MySet=set(MyList)
- Print MySet.
Answer: {2, 4, 6, 8, 10}
Remember: A set has no duplicate elements, and its values may appear in a different order when printed.
Set Operations
Python set operations
| Operation | What it includes |
|---|---|
| Union: | or union() | All elements from both sets. |
| Intersection: & or intersection() | Elements common to both sets. |
| Difference: - or difference() | Elements in the first set but not in the second. |
| Symmetric difference: ^ or symmetric_difference() | Elements in either set, but not the elements common to both. |
Worked example
Find the set operations for set_A={'A', 2, 4, 'D'} and set_B={'A', 'B', 'C', 'D'}.
Try it first, then show the solutionSolution
- Use set_A | set_B or set_A.union(set_B) for union.
- Use set_A & set_B or set_A.intersection(set_B) for intersection.
- Use set_A - set_B or set_A.difference(set_B) for difference.
- Use set_A ^ set_B or set_A.symmetric_difference(set_B) for symmetric difference.
Answer: Union: {2, 4, 'A', 'D', 'B', 'C'}; Intersection: {'A', 'D'}; Difference: {2, 4}; Symmetric difference: {2, 4, 'B', 'C'}.
A program can build a set of even numbers using set([x*2 for x in range(1,11)]). It can build a prime-number set by checking numbers in range(2,20) and adding those that pass its divisibility check. The program can then display the union, intersection, difference and symmetric difference of the two sets.
Results of the even-number and prime-number set program
- Even Numbers: {2, 4, 6, 8, 10, 12, 14, 16, 18, 20}
- Prime Numbers: {2, 3, 5, 7, 11, 13, 17, 19}
- Union: {2, 3, 4, 5, 6, 7, 8, 10, 11, 12, 13, 14, 16, 17, 18, 19, 20}
- Intersection: {2}
- Difference: {4, 6, 8, 10, 12, 14, 16, 18, 20}
- Symmetric Difference: {3, 4, 5, 6, 7, 8, 10, 11, 12, 13, 14, 16, 17, 18, 19, 20}
Creating and Understanding Dictionaries
Definition
- Dictionary
- A dictionary is a collection that stores each element with a key, using key-value pairs inside curly braces.
A colon separates a key from its value, and commas separate the pairs. Dictionary keys must be unique and case sensitive. A dictionary can be empty, or it can contain pairs such as 'RollNo': '1234'.
Dictionary_Name = {Key_1: Value_1, Key_2: Value_2, ..., Key_n: Value_n}
Each Key is paired with its Value.
Dict = {expression for variable in sequence [if condition]}
The expression is evaluated for each variable in the sequence. The optional if condition selects which values are evaluated.
Worked example
Create a dictionary using a comprehension.
Try it first, then show the solutionSolution
- Use Dict = { x : 2 * x for x in range(1,10)}.
- Each key is x, and its value is 2 * x.
Answer: {1: 2, 2: 4, 3: 6, 4: 8, 5: 10, 6: 12, 7: 14, 8: 16, 9: 18}
Accessing and Changing Dictionary Elements
Dictionary actions
- Print the dictionary to access all its elements.
- Use square brackets with a key, such as MyDict['Name'], to access one value.
- Assign a value with dictionary_name[key] = value/element to add a key-value pair.
- Assign a new value to an existing key to overwrite its old value.
- Use del dictionary_name[key] to delete one pair.
- Use dictionary_name.clear() to delete all pairs.
- Use del dictionary_name to delete the entire dictionary.
Worked example
What happens when elements are deleted from Dict = {'Roll No' : 12001, 'SName' : 'Meena', 'Mark1' : 98, 'Marl2' : 86}?
Try it first, then show the solutionSolution
- del Dict['Mark1'] removes the Mark1 pair.
- Dict.clear() removes all remaining pairs.
- del Dict removes the dictionary itself.
- Trying to print Dict after deleting it gives a NameError.
Answer: After deleting Mark1, Dict contains {'Roll No': 12001, 'SName': 'Meena', 'Marl2': 86}. After clear(), it is { }. After del Dict, the name Dict is no longer defined.
Remember: Use the key inside square brackets to access its value. Assigning to a key changes that key's value, while del can remove a pair or the whole dictionary.
Lists, Tuples, Sets and Dictionaries
Python has four collection data types: List, Tuple, Set and Dictionary. A List is an ordered sequence of elements, written inside square brackets. Each element has an index that begins with zero.
Key features of collections
- Python allows positive and negative index values for lists.
- A for loop can access list elements one by one.
- append(), extend() and insert() add elements to a list.
- del, remove() and pop() delete elements from a list.
- Tuples contain comma-separated values inside parentheses. A tuple with one element is called a Singleton tuple.
- Iterating tuples is faster than iterating lists.
- A Set is a mutable, unordered collection without duplicates. Its elements are placed inside curly brackets.
- A Dictionary is a mixed collection of elements.
List and Dictionary Differences
How lists and dictionaries work
| List | Dictionary |
|---|---|
| An ordered set of elements. | Matches one element, called a Key, with another element, called a Value. |
| An index is used to access a particular element. | A key represents the index. A key may be a number or a string. |
| Used to look up a value. | Used to take one value and look up another value. |
Remember: A list uses index values to access elements, while a dictionary uses keys to match values.
Python Collection Practice Tasks
Programming tasks for revision
- Remove duplicates from a list.
- Print the maximum value in a Tuple.
- Find the sum of all numbers in a Tuple using a while loop.
- Find the sum of all even numbers in a list.
- Reverse a list using a loop.
- Insert a value into a list at a specified location.
- Create a list of numbers from 1 to 50 that are divisible by 3 or divisible by 6.
- Create a list of numbers in the range 1 to 20, then delete numbers divisible by 3.
- Count how many times a value appears in a list using a loop.
- Print the maximum and minimum values in a dictionary.
Questions students ask
Short, direct answers to what students search for in this chapter.
What is a list in Python?
A list in Python is an ordered collection of values written inside square brackets [ ]. Its values are called elements, and each element has an index that starts at zero. Lists can contain different types of values, and their elements can be replaced, added, or removed.
How do positive and negative list indexes work in Python?
A positive index counts from the beginning of a list, starting at zero. A negative index counts backward from the end. For Marks = [10, 23, 41, 75], Marks[0] is 10 and Marks[-1] is 75.
What is a nested list in Python?
A nested list is a list that contains another list as one of its elements. For example, Mylist = [ “Welcome”, 3.14, 10, [2, 4, 6] ] includes [2, 4, 6] as an element inside the outer list.
What does len() do to a Python list?
The len() function returns the number of elements in a list. If one of those elements is itself a list, len() counts that inner list as one element. It can also be used as the limit in a loop that reads all list elements.
How does a for loop access Python list elements?
A for loop takes the elements of a list one by one. The loop variable represents the current element, so a statement such as for x in Marks: followed by print( x ) prints each element of Marks in order.
How do I change an element in a Python list?
Use the assignment operator = with the element's index. For example, MyList[2] = 6 replaces the value at index 2 with 6. Python lists are mutable, so their elements can be changed.
Show 21 more questions
What is the difference between append() and extend() in Python?
append() adds a single element to the end of a list. extend() adds more than one element to an existing list. Put the multiple elements for extend() inside square brackets, as in Mylist.extend([71, 32, 29]).
How do I insert an element at a specific position in a Python list?
Use List.insert(position index, element). For example, MyList.insert(3, 'Ramakrishnan') inserts 'Ramakrishnan' at index 3, which is the 4th position. Existing elements from that position shift one place to the right.
What is the difference between del, remove(), pop(), and clear() in Python lists?
del deletes an element by index, a range, or the entire list. remove() deletes a specified element. pop() deletes and returns one element, using an index or the last element if no index is given. clear() removes all elements but keeps the list.
How does range() work in Python?
range() generates a series of values. It can take a start value, an end value, and an optional step value. The end value is excluded, so range(1, 11) generates values from 1 through 10.
How do I create a list from range() in Python?
Pass range() to list(). For example, Even_List = list(range(2,11,2)) creates the list [2, 4, 6, 8, 10]. The list() function converts the series generated by range() into a list.
What is a list comprehension?
A list comprehension is a short way to create a list by applying an expression to values generated by a range. For example, [ x ** 2 for x in range(1,11) ] creates a list of squares from 1 through 10.
What do the count() and index() list functions do?
count(value) returns how many times a value occurs in a list. index(element) returns the index of the first matching element. For example, in [36 ,12 ,12], count(12) is 2 and index(12) is 1.
How do I sort a Python list in descending order?
Call the list's sort() function with reverse=True. For example, MyList.sort(reverse=True) sorts the list in descending order. Without that argument, sorting is in ascending order. sort() changes the original list.
What is the difference between a tuple and a list in Python?
A list is mutable, so its elements can be changed. A tuple is immutable, so its elements cannot be changed after creation. Lists use square brackets, while tuples are usually written with parentheses. Iterating through a tuple is faster than iterating through a list.
How do you create a single-element tuple in Python?
Put a comma after the single element, as in MyTup5 = (10,). Without the comma, as in MyTup4 = (10), Python treats the value as an ordinary data type. A tuple containing one element is called a “Singleton” tuple.
How do you access elements of a tuple using slicing?
Use a slice with the tuple’s index numbers. For example, Tup1[2:5] accesses elements at indices 2 through 4. Tup1[:5] starts from the beginning, Tup1[4:] continues from index 4 to the end, and Tup1[:] accesses the whole tuple.
How does tuple assignment swap two values?
Assign the variables in reverse order: (a, b) = (b, a). Python assigns each value to its matching variable, so the original value of b goes to a and the original value of a goes to b. The values are exchanged without changing their contents.
How can a Python function return more than one value?
A function can return multiple values together as a tuple. For example, Min_Max(n) returns (a, b), where a is max(n) and b is min(n). The returned values can then be assigned separately using (Max_Num, Min_Num) = Min_Max(Num).
How do you create a set in Python?
Create a set by placing comma-separated elements inside curly brackets, such as {1,2,3}. You can also use the set() function. A set keeps only one copy of a repeated value, and its elements may appear in a different order when printed.
What is the difference between union and intersection in Python sets?
Union includes all elements from two sets, using | or union(). Intersection includes only elements common to both sets, using & or intersection(). For set_A={'A', 2, 4, 'D'} and set_B={'A', 'B', 'C', 'D'}, their intersection is {'A', 'D'}.
How do you access a value in a Python dictionary?
Use the key inside square brackets after the dictionary name. For example, MyDict['Name'] accesses the value stored with the key 'Name'. To display all dictionary elements, use print(MyDict).
How do you add or delete dictionary elements in Python?
Add a pair by assigning a value to a key, using dictionary_name[key] = value/element. Assigning to an existing key overwrites its old value. Use del dictionary_name[key] to delete one pair, clear() to delete all pairs, or del dictionary_name to delete the entire dictionary.
What is the difference between a list and a dictionary in Python?
A list is an ordered set of elements, and its elements are accessed using index values. A dictionary matches a Key with a Value. In a dictionary, the key represents the index and may be a number or a string.
How do you access elements in a Python list?
Use an index value to access a particular list element. Each list element has a unique index, and indexing begins with zero. Python also allows negative index values. A for loop can access all elements one by one.
Which Python functions add elements to a list?
append(), extend() and insert() are used to add elements to a list. The revision notes identify extend() as the function for adding more than one element to an existing list.
What is a Set in Python?
A Set is a mutable and unordered collection of elements without duplicates. It is created by placing its elements, separated by commas, within a pair of curly brackets.
Book back answers
23 textbook exercises, solved and checked against the book. Questions we could not prove are left out.
Choose the best answer (1 Marks)
Pick odd one in connection with collection data type
- (a) List
- (b) Tuple
- (c) Dictionary
- (d) Loop
Try it, then show the answerAnswer
(d) Loop
List, tuple and dictionary are collection data types; a loop is not one of them.
From the book: “Python programming language has four collections of data types such as List, Tuples, Set and Dictionary.”
Let list1=[2,4,6,8,10], then print(List1[-2]) will result in
- (a) 10
- (b) 8
- (c) 4
- (d) 6
Try it, then show the answerAnswer
(b) 8
Negative indexing counts backward from the end. Index -2 selects the second-to-last value, 8.
From the book: “python sets -1 as the index value for the last element in list and -2 for the preceding element”
Which of the following function is used to count the number of elements in a list?
- (a) count()
- (b) find()
- (c) len()
- (d) index()
Try it, then show the answerAnswer
(c) len()
The len() function returns the number of elements in a list.
From the book: “The len() function in Python is used to find the length of a list. (i.e., the number of elements in a list).”
If List=[10,20,30,40,50] then List[2]=35 will result
- (a) [35,10,20,30,40,50]
- (b) [10,20,30,40,50,35]
- (c) [10,20,35,40,50]
- (d) [10,35,30,40,50]
Try it, then show the answerAnswer
(c) [10,20,35,40,50]
List indices begin at zero, so index 2 refers to the third element. Assignment replaces 30 with 35.
From the book: “A list element or range of elements can be changed or altered by using simple assignment operator =.”
Practice
What does len() return when used on a list containing an inner list?
Exam questions
Practice questions with model answers. These are not from an official paper.
Explain how positive and negative indices locate elements in a list.2 marks
Positive indices count from the start of the list, beginning at zero. Negative indices count backward from the end, with -1 referring to the last element.
State two differences between a list and a tuple.2 marks
A list is mutable, while a tuple is immutable. List elements are enclosed in square brackets, while tuple elements are enclosed in parentheses.
Explain the difference between append() and extend() for lists.2 marks
append() adds one element to the end of a list. extend() adds more than one element, supplied as a collection, to an existing list.
Describe the four set operations taught in this lesson.5 marks
Python supports four set operations: union, intersection, difference and symmetric difference. These operations can be performed on sets.
- Union: Union combines the elements of the sets.
- Intersection: Intersection gives the elements common to the sets.
- Difference: Difference gives elements in one set that are not in the other set.
- Set properties: Sets are unordered collections without duplicate elements. These properties make sets useful for membership testing and eliminating duplicates.
Example: The chapter proposes generating a set of prime numbers and another set of even numbers, then demonstrating the four operations.
The four operations are union, intersection, difference and symmetric difference.
Watch out
- Do not assume that tuples can be changed like lists; tuples are immutable.
- Do not expect a set to preserve element order or keep duplicate values.
Still stuck on this lesson?
Get an AI answer grounded in your actual textbook — with the exact page reference.
Ask AI about this topic →