Python Tuples

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 9

Python Lists - Quick Notes

A list in Python is a versatile, mutable, and ordered collection of items. Lists can contain
elements of different data types, such as integers, strings, floats, or even other lists. Unlike
tuples, lists can be changed after creation (they are mutable).

Key Features of Lists:

1. Ordered: Items in a list have a defined order, and that order will not change unless
explicitly modified.
2. Mutable: You can change, add, or remove items from a list after it’s been created.
3. Heterogeneous: Lists can contain items of different types (e.g., integers, strings, other
lists).
4. Allows Duplicates: Lists can have repeated elements.
5. Dynamic: Lists can grow or shrink in size as elements are added or removed.

Creating a List:

1. Empty List:

python
Copy code
my_list = []

2. List with Elements:

python
Copy code
my_list = [1, 2, 3, "apple", "banana"]

3. Nested List:
o Lists can contain other lists (nested lists).

python
Copy code
my_list = [1, [2, 3], ["apple", "banana"]]

4. List from a Sequence (e.g., range):

python
Copy code
my_list = list(range(5)) # Output: [0, 1, 2, 3, 4]

Accessing List Elements:

1. Indexing: Access list elements using an index (starting from 0).


python
Copy code
my_list = [10, 20, 30, 40]
print(my_list[0]) # Output: 10

2. Negative Indexing: Access elements from the end of the list.

python
Copy code
print(my_list[-1]) # Output: 40

3. Slicing: Get a subpart of a list using slicing.

python
Copy code
print(my_list[1:3]) # Output: [20, 30]

Modifying Lists:

1. Changing Elements: Lists are mutable, so elements can be updated.

python
Copy code
my_list = [10, 20, 30]
my_list[1] = 25
print(my_list) # Output: [10, 25, 30]

2. Adding Elements:
o append(): Adds an element to the end of the list.

python
Copy code
my_list.append(40)
print(my_list) # Output: [10, 25, 30, 40]

o insert(): Inserts an element at a specific index.

python
Copy code
my_list.insert(1, 15)
print(my_list) # Output: [10, 15, 25, 30, 40]

o extend(): Adds multiple elements (another list) at the end.

python
Copy code
my_list.extend([50, 60])
print(my_list) # Output: [10, 15, 25, 30, 40, 50, 60]

3. Removing Elements:
o remove(): Removes the first occurrence of a specific element.

python
Copy code
my_list.remove(25)
print(my_list) # Output: [10, 15, 30, 40, 50, 60]

o pop(): Removes and returns the element at a specific index. If no index is


specified, it removes the last element.

python
Copy code
my_list.pop() # Removes 60
print(my_list) # Output: [10, 15, 30, 40, 50]

o clear(): Removes all elements from the list.

python
Copy code
my_list.clear()
print(my_list) # Output: []

List Operations:

1. Concatenation: Combine two lists using the + operator.

python
Copy code
list1 = [1, 2]
list2 = [3, 4]
result = list1 + list2
print(result) # Output: [1, 2, 3, 4]

2. Repetition: Repeat the list using the * operator.

python
Copy code
my_list = [1, 2]
print(my_list * 3) # Output: [1, 2, 1, 2, 1, 2]

3. Length of a List:

python
Copy code
my_list = [1, 2, 3, 4]
print(len(my_list)) # Output: 4

List Methods:

1. sort(): Sorts the list in ascending order.

python
Copy code
my_list = [3, 1, 4, 2]
my_list.sort()
print(my_list) # Output: [1, 2, 3, 4]
2. reverse(): Reverses the elements of the list.

python
Copy code
my_list.reverse()
print(my_list) # Output: [4, 3, 2, 1]

3. index(): Returns the index of the first occurrence of a specific element.

python
Copy code
my_list = [10, 20, 30]
print(my_list.index(20)) # Output: 1

4. count(): Returns the number of occurrences of a specific element.

python
Copy code
my_list = [1, 2, 2, 3]
print(my_list.count(2)) # Output: 2

5. copy(): Returns a shallow copy of the list.

python
Copy code
my_list = [1, 2, 3]
copied_list = my_list.copy()
print(copied_list) # Output: [1, 2, 3]

List Comprehension:

List comprehensions provide a concise way to create lists by applying an expression to each
element in a sequence.

1. Basic List Comprehension:

python
Copy code
squares = [x**2 for x in range(5)]
print(squares) # Output: [0, 1, 4, 9, 16]

2. List Comprehension with Condition:

python
Copy code
even_squares = [x**2 for x in range(10) if x % 2 == 0]
print(even_squares) # Output: [0, 4, 16, 36, 64]

Iterating Through a List:

1. Using a for Loop:


python
Copy code
my_list = ["apple", "banana", "cherry"]
for item in my_list:
print(item)

2. Using enumerate() to Get Index and Value:

python
Copy code
for index, value in enumerate(my_list):
print(f"Index: {index}, Value: {value}")

List vs Tuple:

Feature List Tuple


Mutability Mutable (can be changed) Immutable (cannot be changed)
Syntax my_list = [1, 2, 3] my_tuple = (1, 2, 3)
Performance Slightly slower due to mutability Faster due to immutability
Use Case Frequently modified data Fixed, read-only data

Example Program Using Lists:


python
Copy code
# Defining a list
fruits = ["apple", "banana", "cherry"]

# Adding an item
fruits.append("orange")
print(fruits) # Output: ['apple', 'banana', 'cherry', 'orange']

# Inserting an item
fruits.insert(1, "blueberry")
print(fruits) # Output: ['apple', 'blueberry', 'banana', 'cherry',
'orange']

# Removing an item
fruits.remove("banana")
print(fruits) # Output: ['apple', 'blueberry', 'cherry', 'orange']

# Sorting the list


fruits.sort()
print(fruits) # Output: ['apple', 'blueberry', 'cherry', 'orange']

# List comprehension to create a list of squares


squares = [x**2 for x in range(5)]
print(squares) # Output: [0, 1, 4, 9, 16]
Python Tuples - Quick Notes

A tuple in Python is an ordered, immutable collection of items. Tuples are similar to lists, but
unlike lists, once a tuple is created, it cannot be modified.

Key Features of Tuples:

1. Ordered: Elements in a tuple have a defined order.


2. Immutable: Once a tuple is created, its elements cannot be changed, added, or
removed.
3. Heterogeneous: A tuple can contain elements of different data types (e.g., integers,
strings, lists, etc.).
4. Allows Duplicates: Tuples can have repeated elements.
5. Faster: Operations on tuples are generally faster than on lists due to their
immutability.

Creating a Tuple:

1. Empty Tuple:

python
Copy code
my_tuple = ()

2. Tuple with Single Element:


o To create a tuple with a single element, you must include a trailing comma.

python
Copy code
my_tuple = (5,)

3. Tuple with Multiple Elements:

python
Copy code
my_tuple = (1, 2, 3, "apple", "banana")

4. Tuple without Parentheses (tuple packing):


o You can omit parentheses when creating a tuple, although it’s more common
to include them.

python
Copy code
my_tuple = 1, 2, 3, 4
5. Nested Tuple:
o Tuples can contain other tuples.

python
Copy code
my_tuple = (1, (2, 3), (4, 5))

Accessing Tuple Elements:

1. Indexing: Access tuple elements using the index (starting from 0).

python
Copy code
my_tuple = ("apple", "banana", "cherry")
print(my_tuple[0]) # Output: apple

2. Negative Indexing: Access elements from the end of the tuple.

python
Copy code
print(my_tuple[-1]) # Output: cherry

3. Slicing: Get a subpart of a tuple using slicing.

python
Copy code
print(my_tuple[1:3]) # Output: ('banana', 'cherry')

Tuple Operations:

1. Concatenation: Combine two tuples using the + operator.

python
Copy code
tuple1 = (1, 2, 3)
tuple2 = (4, 5)
result = tuple1 + tuple2
print(result) # Output: (1, 2, 3, 4, 5)

2. Repetition: Repeat the tuple using the * operator.

python
Copy code
my_tuple = (1, 2)
print(my_tuple * 3) # Output: (1, 2, 1, 2, 1, 2)

3. Length of a Tuple:

python
Copy code
my_tuple = (1, 2, 3)
print(len(my_tuple)) # Output: 3
Tuple Methods:

1. count(): Returns the number of occurrences of a specified value.

python
Copy code
my_tuple = (1, 2, 2, 3, 4)
print(my_tuple.count(2)) # Output: 2

2. index(): Returns the index of the first occurrence of a specified value.

python
Copy code
my_tuple = (1, 2, 3, 4, 2)
print(my_tuple.index(2)) # Output: 1

Tuple Unpacking:

You can unpack (assign) elements of a tuple to multiple variables.

python
Copy code
my_tuple = (1, 2, 3)
a, b, c = my_tuple
print(a, b, c) # Output: 1 2 3

Immutability of Tuples:

Since tuples are immutable, you cannot:

1. Change individual elements.

python
Copy code
my_tuple = (1, 2, 3)
my_tuple[0] = 5 # Raises TypeError: 'tuple' object does not support
item assignment

2. Append or remove elements.

python
Copy code
my_tuple.append(4) # Raises AttributeError: 'tuple' object has no
attribute 'append'

Tuple vs List:
Feature Tuple List
Mutability Immutable (cannot be changed) Mutable (can be changed)
Syntax my_tuple = (1, 2, 3) my_list = [1, 2, 3]
Performance Faster due to immutability Slightly slower due to mutability
Use Case Fixed data, read-only operations Dynamic data, frequent changes

When to Use Tuples:

 Immutable Data: When you need a collection of items that should not be changed
(e.g., coordinates, days of the week).
 Memory Efficiency: Tuples use less memory compared to lists, making them suitable
for large datasets that don’t need modification.
 Dictionary Keys: Tuples can be used as keys in dictionaries because they are
hashable, unlike lists.

Example Program Using Tuples:


python
Copy code
# Defining a tuple
person = ("John", "Doe", 30)

# Accessing tuple elements


first_name = person[0]
age = person[2]
print(f"First Name: {first_name}, Age: {age}")

# Unpacking the tuple


first, last, age = person
print(f"Name: {first} {last}, Age: {age}")

# Counting occurrences of an element


numbers = (1, 2, 3, 2, 4, 2)
print("Number of 2s:", numbers.count(2))

# Index of first occurrence


print("Index of first 2:", numbers.index(2))

This covers the essential aspects of tuples in Python!

You might also like