Summary: Lists and Tuples in Python
1. Tuples
Ordered sequences of elements.
Written with parentheses:
ratings = (4, 7, "A", 3.5)
Can contain different data types (string, int, float, etc.).
Access elements using indexes:
o ratings[0] → first element
o ratings[-1] → last element
Slicing works like:
o ratings[0:3] → first 3 elements
o ratings[3:5] → last two elements
len(ratings) returns the number of elements.
Immutability
Tuples cannot be changed after creation.
If two variables reference the same tuple, neither can modify it.
To “change” a tuple, you create a new tuple.
sorted() creates a new sorted list, not a tuple.
Nesting
Tuples can contain other tuples:
nt = (1, 2, (3, 4), ("A", "B"))
Access nested values using multiple indices:
o nt[2][1] → 4
o nt[3][0] → "A"
2. Lists
Also ordered sequences, but mutable.
Written using square brackets:
L = ["HardRock", 10, 1.2]
Similar indexing & slicing rules as tuples.
Mutability
Lists can be changed:
Change an element:
L[0] = "Pop"
Delete an element:
del (L[1])
Append one item:
[Link]([2,3])= [“HardRock”, 10, 1.2, [2,3]]
Extend list with multiple items:
[Link]([2, 3])= [“HardRock”, 10, 1.2, 2, 3]
[Link](“A”)= [“HardRock”, 10, 1.2, 2, 3, “A”]
Concatenate lists using +.
Nesting
Lists can contain:
other lists
tuples
mixed data types
Example:
L = [1, [2, 3], ("A", "B")]
Access nested elements:
L[1][0] → 2
L[2][1] → "B"
3. String to List Conversion
Using split():
"A B C".split() → ["A", "B", "C"]
"A,B,C".split(",") → ["A", "B", "C"]
4. Aliasing
Assigning one list to another:
a = [1, 2, 3]
b = a
Both refer to the same list.
Changing a also changes b.
Cloning a list
b = a[:] clones the original list
Now changing a does NOT affect b.
5. Help Function
Get documentation for any object:
help(list)
help(tuple)
List
Package/Method Description Code Example
Syntax:
1. list_name.append(element)
The `append()` method is Example:
append() used to add an element to 1. fruits = ["apple",
the end of a list. "banana", "orange"]
2. [Link]("mango")
print(fruits)
Example 1:
The `copy()` method is used 1. my_list = [1, 2, 3, 4, 5]
copy() to create a shallow copy of 2. new_list = my_list.copy()
a list. print(new_list)
3. # Output: [1, 2, 3, 4, 5]
Example:
The `count()` method is 1. my_list = [1, 2, 2, 3, 4,
used to count the number of 2, 5, 2]
count()
occurrences of a specific 2. count = my_list.count(2)
element in a list in Python. print(count)
3. # Output: 4
A list is a built-in data type
that represents an ordered
and mutable collection of Example:
1. fruits = ["apple",
Creating a list elements. Lists are enclosed "banana", "orange",
in square brackets [] and "mango"]
elements are separated by
commas.
Example:
The `del` statement is used 1. my_list = [10, 20, 30, 40,
to remove an element from 50]
del list. `del` statement removes 2. del my_list[2] # Removes
the element at the specified the element at index 2
print(my_list)
index.
3. # Output: [10, 20, 40, 50]
The `extend()` method is Syntax:
1. list_name.extend(iterable)
used to add multiple
Example:
elements to a list. It takes an 1. fruits = ["apple",
extend() iterable (such as another "banana", "orange"]
list, tuple, or string) and 2. more_fruits = ["mango",
appends each element of the "grape"]
3. [Link](more_fruits)
iterable to the original list. 4. print(fruits)
Example:
Indexing in a list allows you 1. my_list = [10, 20, 30, 40,
to access individual 50]
elements by their position. 2. print(my_list[0])
3. # Output: 10 (accessing
Indexing In Python, indexing starts the first element)
from 0 for the first element 4. print(my_list[-1])
and goes up to 5. # Output: 50 (accessing
`length_of_list - 1`. the last element using
negative indexing)
Syntax:
1. list_name.insert(index,
element)
The `insert()` method is
insert() Example:
used to insert an element. 1. my_list = [1, 2, 3, 4, 5]
2. my_list.insert(2, 6)
3. print(my_list)
Example:
1. my_list = [10, 20, 30, 40,
You can use indexing to 50]
modify or assign new 2. my_list[1] = 25 #
Modifying a list Modifying the second
values to specific elements element
in the list. 3. print(my_list)
4. # Output: [10, 25, 30, 40,
50]
pop() `pop()` method is another Example 1:
way to remove an element 1. my_list = [10, 20, 30, 40,
50]
from a list in Python. It
2. removed_element =
removes and returns the my_list.pop(2) # Removes
element at the specified and returns the element at
index. If you don't provide index 2
an index to the `pop()` 3. print(removed_element)
4. # Output: 30
method, it will remove and 5.
return the last element of
6. print(my_list)
7. # Output: [10, 20, 40, 50]
Example 2:
1. my_list = [10, 20, 30, 40,
50]
2. removed_element =
my_list.pop() # Removes
the list by default and returns the last
element
3. print(removed_element)
4. # Output: 50
5.
6. print(my_list)
7. # Output: [10, 20, 30, 40]
Example:
To remove an element from 1. my_list = [10, 20, 30, 40,
a list. The `remove()` 50]
remove() method removes the first 2. my_list.remove(30) #
occurrence of the specified Removes the element 30
3. print(my_list)
value.
4. # Output: [10, 20, 40, 50]
Example 1:
The `reverse()` method is 1. my_list = [1, 2, 3, 4, 5]
reverse() used to reverse the order of 2. my_list.reverse()
elements in a list print(my_list)
3. # Output: [5, 4, 3, 2, 1]
Syntax:
1. list_name[start:end:step]
Example:
1. my_list = [1, 2, 3, 4, 5]
2. print(my_list[1:4])
3. # Output: [2, 3, 4]
(elements from index 1 to
3)
4.
You can use slicing to 5. print(my_list[:3])
Slicing access a range of elements 6. # Output: [1, 2, 3]
(elements from the
from a list. beginning up to index 2)
7.
8. print(my_list[2:])
9. # Output: [3, 4, 5]
(elements from index 2 to
the end)
10.
11. print(my_list[::2])
12. # Output: [1, 3, 5]
(every second element)
sort() The `sort()` method is used Example 1:
to sort the elements of a list 1. my_list = [5, 2, 8, 1, 9]
2. my_list.sort()
in ascending order. If you
3. print(my_list)
want to sort the list in 4. # Output: [1, 2, 5, 8, 9]
descending order, you can Example 2:
pass the `reverse=True` 1. my_list = [5, 2, 8, 1, 9]
2. my_list.sort(reverse=True)
argument to the `sort()` 3. print(my_list)
method. 4. # Output: [9, 8, 5, 2, 1]
Tuple
Package/Method Description Code Example
Syntax:
1. [Link](value)
The count() method for a
Example:
tuple is used to count 1. fruits = ("apple", "banana",
count() how many times a "apple", "orange")
specified element appears 2. print([Link]("apple"))
in the tuple. #Counts the number of times
apple is found in tuple.
3. #Output: 2
The index() method in a Syntax:
tuple is used to find the 1. [Link](value)
first occurrence of a Example:
specified value and 1. fruits = ("apple", "banana",
index() "orange","apple")
returns its position 2. print([Link]("apple"))
(index). If the value is not #Returns the index value at
found, it raises a which apple is present.
ValueError. 3. #Output: 0
The sum() function in
Python can be used to Syntax:
calculate the sum of all 1. sum(tuple)
sum() elements in a tuple, Example:
1. numbers = (10, 20, 5, 30)
provided that the 2. print(sum(numbers))
elements are numeric 3. #Output: 65
(integers or floats).
Example:
Find the smallest (min()) 1. numbers = (10, 20, 5, 30)
2. print(min(numbers))
min() and max() or largest (max()) 3. #Output: 5
element in a tuple. 4. print(max(numbers))
5. #Output: 30
Syntax:
1. len(tuple)
Example:
Get the number of 1. fruits = ("apple", "banana",
len() elements in the tuple "orange")
using len(). 2. print(len(fruits)) #Returns
length of the tuple.
3. #Output: 3
Dictionaries in Python
What a Dictionary Is
A dictionary is a Python collection that stores data as key–value pairs. Unlike lists, which use
numeric indexes, dictionaries use keys to access values. Keys act like addresses and are
usually strings.
Structure of a Dictionary
Dictionaries are created with curly brackets. Keys must be immutable and unique. Each key
is followed by a value, separated by a colon. Values can be of any data type and can be
duplicated. Key–value pairs are separated by commas.
{“thriller”: 1982, “back in black: 1980, “the dark side of the moon”: 1973, “the bodyguard”:
1992}
Accessing Values
To retrieve a value, you place its key inside square brackets. The key returns the associated
value, such as a release year. DICT[“thriller”]
Adding and Removing Items
You can add a new entry by assigning a value to a new key. Entries can be removed using the
del statement, which deletes both the key and its value.
DICT[“graduation”]=”2007”
Del(DICT[“thriller”])
Checking Membership
The “the bodyguard” in DICT operator checks whether a key exists in the dictionary. It
returns True if the key is present and False if it is not.
Viewing Keys and Values
The keys() method returns all dictionary keys, and the values() method returns all values.
[Link]()=
[Link]()=
Syntax:
1. 1
1. items_list =
Retrieves all key-value pairs as tuples and converts them list(dict_name.items()
into a list of tuples. Each tuple consists of a key and its
corresponding value. )
Example:
1. 1
1. info =
list([Link]())
Overview of Sets
Sets are a Python collection type that can store different data types. They are unordered,
meaning they do not keep track of element positions, and they only contain unique elements
with no duplicates.
Creating Sets and Typecasting
Sets are defined using curly brackets. If duplicate items are included, Python automatically
removes them when the set is created. A list can be converted to a set using the set()
function, which removes duplicates in the process. Set(list)
Modifying Sets
You can add elements to a set using the [Link]() method. Adding the same element
again has no effect because sets cannot contain duplicates. Items can be removed using the
[Link]() method.
Membership Testing
The in operator checks whether an element exists in a set and returns True or False
accordingly. “set element” in set
Set Operations
Python supports several mathematical set operations.
Intersection
The intersection of two sets contains only the elements present in both sets. In Python, the
ampersand (set1 & set 2) operator performs this operation.
Union
The union of two sets includes all elements from both sets. This operation combines the
contents of both sets into a new one. [Link](set2)
To find elements only in set1 [Link](set2)
To find the intersection between the 2 sets [Link](set2)
Subset Checking
A set is considered a subset of another if all its elements are contained within the other set.
This can be checked using the [Link](set1) method.
[Link](set2)
sym_diff = fruits.symmetric_difference(colors)