Lists and Tuples in Python (Part-5)

Posted by

Lists in Python -1

The agenda includes:

  1. Lists in Python – likely an introduction to what lists are and how they are used in Python.
  2. Access List Items – discussing how to retrieve elements from a list.
  3. Change List Items – covering how to modify elements within a list.
  4. Add List Items – explaining methods to add new items to a list.
  5. Remove List Items – detailing how to delete items from a list.
  1. Purpose of Lists: Lists are used to store multiple items in a single variable, making them useful for collecting a group of related data.
  2. Characteristics of Lists:
    • Ordered: The items have a defined order, which will not change unless explicitly reordered.
    • Changeable: You can change, add, and remove items in a list after it has been created.
    • Allow Duplicates: Lists can have items with the same value more than once.
  3. Comparison with Other Data Types: Lists are one of four built-in data types in Python designed for storing collections of data. The other three are:
    • Tuple: Ordered and unchangeable; allows duplicate values.
    • Set: Unordered, unindexed, and no duplicate values allowed.
    • Dictionary: Unordered (as of Python 3.7, dictionaries are ordered), changeable, and indexed by keys, which must be unique.

Access List Items

  • Indexed Access: List items are indexed, allowing you to access them by referring to their index number.
  • Positive Indexing: A positive index accesses items from the beginning of the list, starting at 0.
  • Negative Indexing: A negative index accesses items from the end of the list, where -1 refers to the last item, -2 to the second last, and so on.
  • Range of Indexes: You can specify a range of indexes by defining where to start and where to end the slice. This returns a new sublist.
  • Presence Check: To check if a specific item is present in the list, use the in keyword.

Changing List Items

  • Modifying a Specific Item: To change the value of a specific item in a list, refer to it by its index number. For example, list[index] = new_value.
  • Modifying a Range of Items: To change a range of list items, refer to the range of indices where you want to insert new values. This can be done using slicing to set multiple values at once, e.g., list[start_index:end_index] = [new_values].

Adding Items to a List

  • Append to End of List: Use the append() method to add an item to the end of the list. For example, list.append(item) adds item to the end of list.
  • Insert at Specific Index: To insert an item at a specified index, use the insert() method, not index(). For example, list.insert(index, item) places item at the specified index, shifting other items to the right.
  • Append Multiple Items: Use the extend() method to add items from another list (or any iterable) to the end of the current list. For example, list.extend([item1, item2]) adds item1 and item2 to the end of list.

Remove List Items

  • The remove() method removes the specified item
  • The pop() method removes the specified index. If we donโ€™t specify an index then pop() will remove the last item from the list
  • โ€œdelโ€ Keyword also removes specified Index
  • clear() method empties the list

examples:

. Creating a List

# List of numbers
numbers = [1, 2, 3, 4, 5]

# List of strings
names = ["Alice", "Bob", "Charlie"]

# Mixed data types
mixed = [1, "Alice", True, 3.14]

Accessing List Elements

# Access the first item of names
first_name = names[0]  # Output: 'Alice'

# Access the last item of numbers
last_number = numbers[-1]  # Output: 5

Adding Elements to a List

You can add items to a list using append() or extend():

# Remove a specific element
names.remove("Charlie")  # Now names is ["Alice", "Bob", "Diana", "Eric"]

# Pop the last item from the list
last_popped = numbers.pop()  # Removes 6 and returns it

# Delete an item by index
del numbers[0]  # Removes 1 from the list

Removing Elements from a List

# Remove a specific element
names.remove("Charlie")  # Now names is ["Alice", "Bob", "Diana", "Eric"]

# Pop the last item from the list
last_popped = numbers.pop()  # Removes 6 and returns it

# Delete an item by index
del numbers[0]  # Removes 1 from the list

List Slicing

# Elements from index 1 to 3
slice_of_numbers = numbers[1:4]  # Output: [2, 3, 4]

# All elements from the beginning to index 2
start_slice = numbers[:3]  # Output: [2, 3]

List Comprehensions

# Create a list of squares of the first 10 numbers
squares = [x**2 for x in range(1, 11)]

Modifying a Specific Item:

fruits = ['apple', 'banana', 'cherry']
fruits[1] = 'blueberry'  # Change 'banana' to 'blueberry'
print(fruits)  # Output: ['apple', 'blueberry', 'cherry']

Modifying a Range of Items:

fruits = ['apple', 'banana', 'cherry', 'date', 'elderberry']
fruits[1:4] = ['blackberry', 'coconut']  # Replace items from index 1 to 3
print(fruits)  # Output: ['apple', 'blackberry', 'coconut', 'elderberry']

Append to End of List:

fruits = ['apple', 'banana', 'cherry']
fruits.append('date')  # Add 'date' to the end
print(fruits)  # Output: ['apple', 'banana', 'cherry', 'date']

Insert at Specific Index:

fruits = ['apple', 'banana', 'cherry']
fruits.insert(1, 'blackberry')  # Insert 'blackberry' at index 1
print(fruits)  # Output: ['apple', 'blackberry', 'banana', 'cherry']

Append Multiple Items:

fruits = ['apple', 'banana', 'cherry']
more_fruits = ['elderberry', 'fig']
fruits.extend(more_fruits)  # Add multiple items to the end
print(fruits)  # Output: ['apple', 'banana', 'cherry', 'elderberry', 'fig']

The remove() Method:

fruits = ['apple', 'banana', 'cherry', 'banana']
fruits.remove('banana')  # Removes the first 'banana'
print(fruits)  # Output: ['apple', 'cherry', 'banana']

The pop() Method:

fruits = ['apple', 'banana', 'cherry']
removed_item = fruits.pop()  # Removes 'cherry'
print(removed_item)  # Output: 'cherry'
print(fruits)  # Output: ['apple', 'banana']

The del Keyword:

fruits = ['apple', 'banana', 'cherry']
del fruits[1]  # Removes 'banana'
print(fruits)  # Output: ['apple', 'cherry']

del fruits  # Deletes the entire list

The clear() Method:

fruits = ['apple', 'banana', 'cherry']
fruits.clear()
print(fruits)  # Output: []

Lists in Python -2

Agenda

  1. Loop through a list
    • Discusses how to iterate over each item in a list, typically using a for loop.
  2. Sort list
    • Explores methods to sort the items in a list, either in ascending or descending order, or based on custom criteria.
  3. Copy list
    • Details methods to create a new list that is a copy of an existing list, ensuring that modifications to the new list do not affect the original.
  4. Join list
    • Describes how to concatenate or combine multiple lists into a single list.
  5. List Methods
    • Reviews various built-in Python list methods that provide functionality like adding, removing, or altering items in a list.

Loop through a list

my_list = ['apple', 'banana', 'cherry']
for item in my_list:
    print(item)

Sort list

my_list = [3, 1, 4, 1, 5, 9, 2]
my_list.sort()
print(my_list)  # Output: [1, 1, 2, 3, 4, 5, 9]

new_sorted_list = sorted(my_list, reverse=True)
print(new_sorted_list)  # Output: [9, 5, 4, 3, 2, 1, 1]

Copy list

original_list = [1, 2, 3]
copied_list = original_list[:]
another_copied_list = list(original_list)

Join list

list_one = [1, 2, 3]
list_two = [4, 5, 6]
joined_list = list_one + list_two
print(joined_list)  # Output: [1, 2, 3, 4, 5, 6]

List Methods

There are various methods you can use with lists. Here are a few:

  • append(): Adds an item to the end of the list.
  • extend(): Adds all elements of a list to another list.
  • pop(): Removes the item at the given position in the list, and returns it.
my_list = ['a', 'b', 'c']
my_list.append('d')
print(my_list)  # Output: ['a', 'b', 'c', 'd']

my_list.pop()
print(my_list)  # Output: ['a', 'b', 'c']

another_list = ['x', 'y', 'z']
my_list.extend(another_list)
print(my_list)  # Output: ['a', 'b', 'c', 'x', 'y', 'z']

1. append()

Purpose: Adds an element at the end of the list.

numbers = [1, 2, 3]
numbers.append(4)
print(numbers)  # Output: [1, 2, 3, 4]

2. clear()

Purpose: Removes all the elements from the list. Example:

numbers = [1, 2, 3]
numbers.clear()
print(numbers)  # Output: []

3. copy()

Purpose: Returns a copy of the list. Example:

original = [1, 2, 3]
copied = original.copy()
print(copied)  # Output: [1, 2, 3]

4. count()

Purpose: Returns the number of elements with the specified value. Example:

items = ['apple', 'banana', 'apple']
print(items.count('apple'))  # Output: 2

5. extend()

Purpose: Adds the elements of a list (or any iterable), to the end of the current list. Example:

list1 = [1, 2, 3]
list2 = [4, 5, 6]
list1.extend(list2)
print(list1)  # Output: [1, 2, 3, 4, 5, 6]

6. index()

Purpose: Returns the index of the first element with the specified value. Example:

fruits = ['apple', 'banana', 'cherry']
print(fruits.index('banana'))  # Output: 1

7. insert()

Purpose: Adds an element at the specified position. Example:

fruits = ['apple', 'banana']
fruits.insert(1, 'orange')
print(fruits)  # Output: ['apple', 'orange', 'banana']

8. pop()

Purpose: Removes the element at the specified position. Example:

fruits = ['apple', 'banana', 'cherry']
fruits.pop(1)
print(fruits)  # Output: ['apple', 'cherry']

9. remove()

Purpose: Removes the item with the specified value. Example:

fruits = ['apple', 'banana', 'cherry']
fruits.remove('banana')
print(fruits)  # Output: ['apple', 'cherry']

10. reverse()

Purpose: Reverses the order of the list. Example:

numbers = [1, 2, 3]
numbers.reverse()
print(numbers)  # Output: [3, 2, 1]

11. sort()

Purpose: Sorts the list. Example:

numbers = [3, 1, 4, 1, 5, 9, 2]
numbers.sort()
print(numbers)  # Output: [1, 1, 2, 3, 4, 5, 9]

Tuples in Python

Tuples

  • Tuples are used to store multiple items in a single variable.
  • Tuple is one of 4 built-in data types in Python used to store collections of data, the other 3 are List, Set, and Dictionary, all with different qualities and usage.
  • A tuple is a collection which is ordered and unchangeable
thistuple = ("apple", "banana", "cherry")
print(thistuple)

To create a tuple with only one item, you must add a comma after the item, otherwise Python will not recognize it as a tuple.

thistuple = ("apple",)
print(type(thistuple))
# NOT a tuple
thistuple = ("apple")
print(type(thistuple))

Update Tuples

  • Tuples are unchangeable, meaning that you cannot change, add, or remove items once the tuple is created.
  • But there is a workaround. You can convert the tuple into a list, change the list, and convert the list back into a tuple.
x = ("apple", "banana", "cherry")
y = list(x)
y[1] = "kiwi"
x = tuple(y)

print(x)


Here’s the transcription of the slide you’ve uploaded about unpacking tuples in Python:


Unpack Tuples

  • When we create a tuple, we normally assign values to it. This is called “packing” a tuple.
  • But, in Python, we are also allowed to extract the values back into variables. This is called “unpacking”.

Example 1: Basic Unpacking

fruits = ("apple", "banana", "cherry")
(green, yellow, red) = fruits

print(green)  # Output: apple
print(yellow)  # Output: banana
print(red)    # Output: cherry

Example 2: Unpacking with * (for multiple remaining values)

fruits = ("apple", "banana", "cherry", "strawberry", "raspberry")
(green, yellow, *red) = fruits

print(green)  # Output: apple
print(yellow)  # Output: banana
print(red)    # Output: ['cherry', 'strawberry', 'raspberry']

Example 3: Advanced Unpacking (Using * in the middle)

fruits = ("apple", "mango", "papaya", "pineapple", "cherry")
(green, *tropic, red) = fruits

print(green)  # Output: apple
print(tropic)  # Output: ['mango', 'papaya', 'pineapple']
print(red)    # Output: cherry

Loop Tuples

Example 1: Using a for loop to iterate directly over the elements of a tuple

thistuple = ("apple", "banana", "cherry")
for x in thistuple:
    print(x)
output:
apple
banana
cherry

Example 2: Using a for loop with range() and len() to iterate over the tuple by index

thistuple = ("apple", "banana", "cherry")
for i in range(len(thistuple)):
    print(thistuple[i])

output:
apple
banana
cherry

Join Tuples

Example 1: Joining two tuples

tuple1 = ("a", "b", "c")
tuple2 = (1, 2, 3)
tuple3 = tuple1 + tuple2
print(tuple3)

output:
('a', 'b', 'c', 1, 2, 3)

Example 2: Repeating a tuple

count()

  • Description: Returns the number of times a specified value occurs in a tuple.
thistuple = ("apple", "banana", "cherry", "apple", "cherry")
print(thistuple.count("apple"))  # Output: 2

index()

  • Description: Searches the tuple for a specified value and returns the position of where it was found.
thistuple = ("apple", "banana", "cherry")
print(thistuple.index("cherry"))  # Output: 2

guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x