5. Python Sequences (65m) Flashcards

1
Q

Explain for loop and explain the following code:

groceries = ['roast beef', 'cucumbers', 'lettuce', 'peanut butter', 'bread', 'dog food']
for item in groceries:
    print(item)
    
name = "Shelley"
for letter in name:
    print(letter)
A

A for loop is a control flow statement in programming that allows you to iterate over a sequence of elements, such as a list, string, or any other iterable object. It repeatedly executes a block of code for each item in the sequence until all the items have been processed.

In the given code:
~~~
groceries = [‘roast beef’, ‘cucumbers’, ‘lettuce’, ‘peanut butter’, ‘bread’, ‘dog food’]
for item in groceries:
print(item)
~~~

The variable groceries is a list that contains different items. The for loop iterates over each item in the groceries list, and in each iteration, it assigns the current item to the variable item. The indented block of code following the for loop is executed for each item. In this case, the code prints each item in the groceries list on a separate line.

Output:
~~~
roast beef
cucumbers
lettuce
peanut butter
bread
dog food
~~~

name = "Shelley"
for letter in name:
    print(letter)

The variable name is a string that contains the value “Shelley”. The for loop iterates over each character in the name string, and in each iteration, it assigns the current character to the variable letter. The indented block of code following the for loop is executed for each character. In this case, the code prints each character in the name string on a separate line.

S
h
e
l
l
e
y

In summary, the first for loop prints each item in the groceries list, while the second for loop prints each character in the name string.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

Explain the following code, mainly the f and using index within.

groceries = ['roast beef', 'cucumbers', 'lettuce', 'peanut butter', 'bread', 'dog food']

index = 1
for item in groceries:
    print(f'{index}. {item}')
    index+=1
A

The code initializes a list called groceries with various items. It also initializes a variable index and sets it to 1.

The for loop iterates over each item in the groceries list. In each iteration, the current item is assigned to the variable item. The indented block of code following the for loop is executed for each item.

Inside the loop, the code uses an f-string to format a string that includes the item’s index and its corresponding value. The {index} and {item} within the f-string are placeholders that will be replaced with the actual values during string formatting. The index variable is used to display the position of the item in the list, while item represents the actual item itself.

The line index += 1 increments the value of index by 1 after each iteration of the loop. This ensures that the index value increases for each item.

As a result, the code will print each item in the groceries list with its corresponding index number. The index starts from 1 and increases by 1 for each item.

Output:
~~~
1. roast beef
2. cucumbers
3. lettuce
4. peanut butter
5. bread
6. dog food
~~~

This approach is useful when you want to display the items in a list along with their respective indices.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

How to do the following using enumerate object in python?

groceries = ['roast beef', 'cucumbers', 'lettuce', 'peanut butter', 'bread', 'dog food']

index = 1
for item in groceries:
    print(f'{index}. {item}')
    index+=1

Output:
~~~
1. roast beef
2. cucumbers
3. lettuce
4. peanut butter
5. bread
6. dog food
~~~

A

You can achieve the same result using the enumerate() function, which returns an enumerate object that generates pairs of indices and items from an iterable. Here’s how you can modify the code using enumerate():

groceries = ['roast beef', 'cucumbers', 'lettuce', 'peanut butter', 'bread', 'dog food']

for index, item in enumerate(groceries, start=1):
    print(f'{index}. {item}')

or

groceries = ['roast beef', 'cucumbers', 'lettuce', 'peanut butter', 'bread', 'dog food']

for index, item in enumerate(groceries, 1):
    print(f'{index}. {item}')

In this updated code:

  • The enumerate() function is used to iterate over the groceries list. It takes two arguments: the iterable (groceries) and the optional start parameter, which determines the starting index. In this case, we set start=1 to begin the index at 1.
  • Inside the loop, the enumerate() function provides two values: index and item. The index represents the current index of the item in the iteration, and item represents the actual item itself.
  • The print() statement remains the same, using an f-string to format the output with the index and item.

With this modification, the code will produce the same output as before, printing each item in the groceries list with its corresponding index number.

Output:
~~~
1. roast beef
2. cucumbers
3. lettuce
4. peanut butter
5. bread
6. dog food
~~~

Using enumerate() simplifies the code by handling the index generation automatically, eliminating the need for an additional variable and manual index incrementation.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q
  1. Write a for loop that iterates over the provided list. The body of the for loop should print the current element in the list.
rainbow = ['red', 'orange', 'yellow', 'green', 'blue', 'indigo', 'violet']
  1. Edit the code so that the for loop uses the enumerate method. Add a print statement above the existing print statement that prints the index of the current element.
A
  1. Answer to 1:
    ~~~
    rainbow = [‘red’, ‘orange’, ‘yellow’, ‘green’, ‘blue’, ‘indigo’, ‘violet’]
    for item in rainbow:
    print(item)
    ~~~
  2. Answer to 2:
    ~~~
    rainbow = [‘red’, ‘orange’, ‘yellow’, ‘green’, ‘blue’, ‘indigo’, ‘violet’]
    for index, item in enumerate(rainbow):
    print(f’{index}. {item}’)
    ~~~

Output:
~~~
0. red
1. orange
2. yellow
3. green
4. blue
5. indigo
6. violet
~~~

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

What is range()? Explain the range method in python?

A

Example 1

In Python, range() is a built-in function that returns a sequence of numbers. It is often used in for loops to iterate over a sequence of numbers a specific number of times.

The range() function can be called with one, two, or three arguments:
1. range(stop): This form generates a sequence of numbers from 0 to stop - 1. The stop parameter specifies the upper bound, and the sequence includes all the numbers starting from 0 up to, but not including, the stop value.

  1. range(start, stop): This form generates a sequence of numbers from start to stop - 1. The start parameter specifies the lower bound (inclusive), and the sequence includes all the numbers starting from start up to, but not including, the stop value.
  2. range(start, stop, step): This form generates a sequence of numbers from start to stop - 1 with a specific step value. The step parameter determines the increment between each number in the sequence. It can be either positive or negative.

The range() function returns an iterable object of type range. To access the actual numbers, you can either convert the range object to a list using list(range()) or use it directly within a loop or any other context where iteration is expected.

Here are a few examples to illustrate the usage of range():
~~~
for num in range(5):
print(num)

Output: 0 1 2 3 4

Example 2
for num in range(2, 8):
print(num)

Output: 2 3 4 5 6 7

Example 3
for num in range(1, 10, 2):
print(num)

Output: 1 3 5 7 9
~~~

In these examples, the range() function is used to generate different sequences of numbers, and a for loop is used to iterate over the numbers and print them.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

Write a for loop that iterates over a range with a stop value of 10 (assume the start value is 0 and the step value is 1).
The body of the for loop should append the current value to the provided list called my_list.
To append a value to a list, use the syntax my_list.append(val).

my_list = []
A

The answer is:

my_list = []
for i in range(10):
    my_list.append(i)
print(my_list)
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

What does the i represent in the following code:

groceries = ['fruit', 'tomatoes', 'paper towels', 'ketchup']

for i, item in enumerate(groceries):
    print(i)
    print(item)
A

The index of the current element in the loop

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

Iterating over a Python range is analogous to traditional for loops in other programming languages, like JavaScript or PHP. True or False?

A

True.

Iterating over a Python range object is analogous to traditional for loops in other programming languages like JavaScript or PHP. The range object in Python provides a way to generate a sequence of numbers that can be used for iteration. This is similar to the use of traditional for loops in other languages, where a loop variable is incremented or decremented on each iteration.

The range object in Python can be used with a for loop to iterate over a sequence of numbers and perform operations or execute a block of code for each value. This iteration behavior is similar to how for loops work in other programming languages.

For example, in JavaScript, you might use a for loop to iterate over a sequence of numbers:
~~~
for (let i = 0; i < 5; i++) {
console.log(i);
}
~~~

In Python, you can achieve the same iteration using a range object:
~~~
for i in range(5):
print(i)
~~~

Both examples produce the same output:
~~~
0
1
2
3
4
~~~

Therefore, iterating over a Python range is indeed analogous to traditional for loops in other programming languages like JavaScript or PHP.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

Explain Slice[] in Python?

A

such as a string, list, or tuple. It allows you to retrieve a subset of elements based on their indices.

The slice notation in Python uses square brackets ([]) to enclose the indices or slice parameters. The basic syntax for slicing is sequence[start:stop:step], where:

  • start represents the index where the slice begins (inclusive).
  • stop represents the index where the slice ends (exclusive).
  • step (optional) specifies the step or increment between elements in the slice.
slice[start:stop:step]

Here are a few examples to illustrate the usage of slicing:
~~~
my_string = “Hello, World!”
my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9]

Slicing a string
print(my_string[7:]) # Output: “World!”
print(my_string[:5]) # Output: “Hello”
print(my_string[7:12]) # Output: “World”

Slicing a list
print(my_list[2:6]) # Output: [3, 4, 5, 6]
print(my_list[::-1]) # Output: [9, 8, 7, 6, 5, 4, 3, 2, 1]
~~~

In the first example, my_string[7:] retrieves a slice starting from index 7 until the end of the string, resulting in “World!”. Similarly, my_string[:5] returns a slice from the beginning of the string up to (but not including) index 5, giving us “Hello”. Lastly, my_string[7:12] extracts a slice from index 7 up to (but not including) index 12, which yields “World”.

In the second example, my_list[2:6] retrieves a slice from index 2 up to (but not including) index 6 of the list, resulting in [3, 4, 5, 6]. The expression my_list[::-1] creates a slice that starts from the end of the list and iterates backward with a step of -1, effectively reversing the order of the list.

Slicing allows you to manipulate or extract subsets of sequences efficiently, making it a powerful feature in Python for working with strings, lists, and other sequence objects.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

Explain the following code:

nums = [1, 2, 3, 4, 5, 6, 7, 8]
nums_partial = nums[0::2] #1,3,5,7
print(nums_partial)

colors = ['red', 'orange', 'yellow', 'green', 'blue', 'indigo', 'violet']
colors_partial = colors[3:6]
print(colors_partial)
A

The given code demonstrates the usage of slicing to extract specific portions of lists in Python:

nums = [1, 2, 3, 4, 5, 6, 7, 8]
nums_partial = nums[0::2]  # 1, 3, 5, 7
print(nums_partial)

In this code snippet, nums is a list containing the numbers 1 through 8. The line nums_partial = nums[0::2] utilizes slicing to create a new list called nums_partial. The slice notation [0::2] specifies the start, stop, and step values for the slice. Here’s what each component means:

  • 0 represents the start index of the slice. In this case, it starts at the beginning of the list.
  • None or an empty space after the second colon (:) represents the stop index. It indicates that the slice should continue until the end of the list.
  • 2 represents the step or the increment value. It specifies that the slice should include every second element.

Therefore, nums_partial is assigned the values [1, 3, 5, 7], which are the elements from the nums list at the indices 0, 2, 4, and 6.

The code then prints nums_partial, resulting in the output:
~~~
[1, 3, 5, 7]
~~~

colors = ['red', 'orange', 'yellow', 'green', 'blue', 'indigo', 'violet']
colors_partial = colors[3:6]
print(colors_partial)

In this part of the code, colors is a list of colors. The line colors_partial = colors[3:6] uses slicing to extract a portion of the colors list. The slice [3:6] includes elements starting from index 3 and ending at index 6 (exclusive). So, it retrieves the elements at indices 3, 4, and 5.

Therefore, colors_partial is assigned the list [‘green’, ‘blue’, ‘indigo’], which represents the subset of colors from indices 3 to 5 in the original colors list.

The code then prints colors_partial, resulting in the output:

['green', 'blue', 'indigo']

In summary, the code showcases how slicing can be used to extract specific portions of lists, allowing you to work with subsets of elements rather than the entire list.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

Create a slice of the provided student_gpas list that includes the 3rd through the 5th elements in the list. Assign the slice to a variable called sliced_gpas.

student_gpas = [4.0, 2.3, 3.5, 3.7, 3.9, 2.8, 1.5, 4.0]
A

The answer is:

student_gpas = [4.0, 2.3, 3.5, 3.7, 3.9, 2.8, 1.5, 4.0]
sliced_gpas = student_gpas[2:5]
print(sliced_gpas)
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

Explain len(), min(), max() in python?

A

In Python, len(), min(), and max() are built-in functions that operate on different types of data structures and perform specific operations. Here’s an explanation of each function:

  • len(): The len() function is used to determine the length or size of an object. It takes a sequence or collection (such as a string, list, tuple, or dictionary) as its argument and returns the number of elements or characters in that object. For example:
    ~~~
    my_list = [1, 2, 3, 4, 5]
    print(len(my_list)) # Output: 5

my_string = “Hello, World!”
print(len(my_string)) # Output: 13
~~~

  • min(): The min() function returns the smallest element from a sequence or a set of arguments. It can be used with various data types like numbers, strings, or even custom objects, as long as they support comparison operations. When used with multiple arguments, it returns the minimum value among all the provided arguments. Here are a few examples:
    ~~~
    my_list = [5, 2, 9, 1, 7]
    print(min(my_list)) # Output: 1

my_string = “hello”
print(min(my_string)) # Output: ‘e’

print(min(2, 8, 3, 1)) # Output: 1
~~~

  • max(): The max() function is the counterpart of min(). It returns the largest element from a sequence or a set of arguments. Like min(), it can be used with various data types and returns the maximum value among the provided arguments. Here are a few examples:
    ~~~
    my_list = [5, 2, 9, 1, 7]
    print(max(my_list)) # Output: 9

my_string = “hello”
print(max(my_string)) # Output: ‘o’

print(max(2, 8, 3, 1)) # Output: 8
~~~

These functions are powerful tools in Python for obtaining information about the size, minimum, and maximum values within data structures or sequences. They can be handy for various purposes, such as data analysis, finding extremes, or verifying conditions based on size or range.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

when mixed = “treehouse2019”, if len(), min(), max() run on this what will each return and why?

A

If you have the variable mixed assigned with the value “treehouse2019” and you run len(mixed), min(mixed), and max(mixed), here’s what each function will return and why:

  • len(mixed): The len() function will return the length of the string mixed. In this case, the string has a length of 13 characters, so len(mixed) will return 13.
  • min(mixed): The min() function, when applied to a string, returns the smallest character based on the ASCII values. In this case, the smallest character in “treehouse2019” is “0” because “0” has the lowest ASCII value. Therefore, min(mixed) will return “0”.
  • max(mixed): The max() function, when used with a string, returns the largest character based on the ASCII values. In this case, the largest character in “treehouse2019” is “u” because “u” has the highest ASCII value. Hence, max(mixed) will return “u”.

So, the results would be:

len(mixed) returns 13
min(mixed) returns “0”
max(mixed) returns “u”

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

What does ASCII values mean?

A

ASCII (American Standard Code for Information Interchange) is a character encoding standard that assigns numeric values to characters. It is a widely used encoding scheme that represents a set of 128 characters, including uppercase and lowercase letters, digits, punctuation marks, control characters, and special symbols.

In ASCII, each character is represented by a unique 7-bit binary number (ranging from 0 to 127). These binary numbers are often represented in decimal form for convenience. For example, the ASCII value for the uppercase letter “A” is 65, the ASCII value for the digit “0” is 48, and the ASCII value for the lowercase letter “a” is 97.

The ASCII values provide a way to represent characters in a standardized manner, allowing computers to understand and process text. By using ASCII values, it becomes possible to compare and order characters based on their numerical representations. This is why functions like min() and max() can determine the smallest and largest characters in a string by comparing their ASCII values.

It’s important to note that ASCII is limited to representing 128 characters and does not support characters from non-English languages or special characters used in various writing systems. To support a broader range of characters and languages, other character encoding standards like Unicode were developed.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

What is lexicographical ordering?

A

Lexicographical ordering, also known as lexicographic order or dictionary order, is a way of arranging elements based on their order in an underlying dictionary or alphabet. It is a common method of sorting or comparing strings or sequences of characters.

In lexicographical ordering, elements are compared character by character from left to right. The comparison is done based on the ASCII or Unicode values of the characters. The element that has the smaller or lower value at the first differing character is considered smaller or comes before in lexicographical order.

Here are a few examples to illustrate lexicographical ordering:

  1. Comparing strings: “apple” comes before “banana” because “a” comes before “b” in the English alphabet. “cat” comes before “catch” because all characters are the same up to the third position, and “t” comes before “tch”.
  2. Sorting a list of strings in lexicographical order: Given the list: [“banana”, “apple”, “cat”]
    After sorting in lexicographical order, the list becomes: [“apple”, “banana”, “cat”]
  3. Comparing numbers as strings: “123” comes before “456” because “1” comes before “4” in the ASCII/Unicode table.
    Lexicographical ordering is a fundamental concept used in various programming tasks, such as sorting, searching, and comparing strings. It provides a way to establish a consistent and predictable order for elements based on their textual representations.

Treehouse:
* Lexicographical ordering is very similar to alphabetical ordering, but it considers additional characters besides the letters of the alphabet.

Some of the basic rules in Python are that:

  • Uppercase letters come earlier than lowercase letters. This means that A < Z < a < z.
  • Numbers come earlier than letters. This means that 0 < 9 < A < a.
  • Space characters come before all printable characters.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q
  1. Find the len of the provided student_gpas list and assign it to a variable called length.
    ~~~
    student_gpas = [4.0, 2.3, 3.5, 3.7, 3.9, 2.8, 1.5, 4.0]
    ~~~
  2. On a line beneath the existing code, find the max of the provided student_gpas list and assign it to a variable called ‘max_gpa'.
  3. On a line beneath the existing code, find the min of the provided student_gpas list and assign it to a variable called ‘min_gpa’.
A

Answer to 1:
~~~
student_gpas = [4.0, 2.3, 3.5, 3.7, 3.9, 2.8, 1.5, 4.0]
length = len(student_gpas)
~~~

Answer to 2:
~~~
student_gpas = [4.0, 2.3, 3.5, 3.7, 3.9, 2.8, 1.5, 4.0]
length = len(student_gpas)
max_gpa = max(student_gpas)
~~~

Answer to 3:
~~~
student_gpas = [4.0, 2.3, 3.5, 3.7, 3.9, 2.8, 1.5, 4.0]
length = len(student_gpas)
max_gpa = max(student_gpas)
min_gpa = min(student_gpas)
~~~

17
Q

Explain the following code:
~~~
docs = ‘Tuples are immutable sequences, typically used to store collections of heterogeneous data (such as the 2-tuples produced by the enumerate() built-in). Tuples are also used for cases where an immutable sequence of homogeneous data is needed (such as allowing storage in a set or dict instance).’

if ‘tuple’ in docs:
print(“tuple is here!”)
else:
print(“tuple is not here!”)

if ‘tuple’ not in docs:
print(“tuple is not here!”)
else:
print(“tuple is here!”)
~~~

A

The given code demonstrates the use of the in operator to check for the presence or absence of a specific substring within a string.

This if statement checks if the substring ‘tuple’ is present in the docs string. The in operator returns True if the substring is found and False otherwise. In this case, since ‘tuple’ is present in docs, the condition evaluates to True, and the corresponding message “tuple is here!” is printed.

In this if statement, the not in operator is used to check if the substring ‘tuple’ is not present in the docs string. If the substring is not found, the condition evaluates to True, and the message “tuple is not here!” is printed. However, since ‘tuple’ is present in docs, the condition evaluates to False, and the alternative message “tuple is here!” is printed.

18
Q

Explain .count() method in Python?

A

In Python, the .count() method is a built-in method that can be used on strings, lists, tuples, and other sequence-like objects. It allows you to count the number of occurrences of a specific element within the object. Here’s an explanation of how the .count() method works:

Syntax:
The syntax for using the .count() method is as follows:
~~~
object.count(element)
~~~

Example 1 - Counting occurrences in a string:
~~~
my_string = “Hello, World!”
count = my_string.count(“o”)
print(count) # Output: 2
~~~

Example 2 - Counting occurrences in a list:
~~~
my_list = [1, 2, 2, 3, 2, 4, 2]
count = my_list.count(2)
print(count) # Output: 4
~~~

19
Q

What does .index() method mean in Python?

A

In Python, the .index() method is a built-in method that can be used on strings, lists, tuples, and other sequence-like objects. It allows you to find the index or position of the first occurrence of a specific element within the object.

The .index() method has the following syntax:
~~~
object.index(element)
~~~

Here’s an example to illustrate the usage of the .index() method:
~~~
my_list = [10, 20, 30, 40, 50]
index = my_list.index(30)
print(index) # Output: 2
~~~

In this example, the .index() method is used on a list (my_list) to find the index of the first occurrence of the number 30. Since 30 is found at index 2, the output will be 2.

The .index() method is useful when you need to determine the position of a specific element within a sequence-like object. It allows you to locate the first occurrence of an element and retrieve its index for further processing or analysis.

Example 2:
~~~
my_string = “Hello, how are you?”
index = my_string.index(“how”)
print(index) # Output: 7
~~~

In this example, the string my_string contains the words “Hello, how are you?”. We use the .index() method to find the index of the first occurrence of the word “how” within the string. Since “how” starts at index 7, the output will be 7.

The .index() method works similarly on strings as it does on other sequence-like objects. It helps locate the first occurrence of a specific substring within a string and returns its index position.

20
Q

Recap:
1. What is List & Tuples?
2. What is Index method?
3. What is Count method?
4. What is Range?

A

Code Samples: Membership Testing, Count, and Index

  • List & Tuples
    Membership Testing
    ~~~
    fruits = [‘apple’, ‘banana’, ‘orange’, ‘pear’, ‘strawberry’]
    vegetables = (‘asparagus’, ‘corn’, ‘broccoli’, ‘eggplant’, ‘onion’)

‘eggplant’ in fruits # False
‘eggplant’ not in fruits # True

‘eggplant’ in vegetables # True
‘eggplant’ not in vegetables # False
~~~

  • Index
    ~~~
    my_pets = (‘dog’, ‘cat’, ‘cat’, ‘chicken’, ‘dog’)

my_pets.index(‘dog’) # 0
my_pets.index(‘chicken’) # 3
my_pets.index(‘lizard’) # ValueError: ‘lizard’ is not in list
~~~

  • Count
    ~~~
    my_pets = [‘dog’, ‘cat’, ‘cat’, ‘chicken’, ‘dog’]

my_pets.count(‘cat’) # 2
my_pets.count(‘lizard’) # 0
~~~

  • Range
    Membership Testing
    ~~~
    nums = range(10)

0 in nums # True
10 in nums # False
4 in nums # True

0 not in nums # False
15 not in nums # True
10 not in nums # True
~~~

Next:
~~~
nums = range(1, 10, 2)

0 in nums # False
6 in nums # False

4 not in nums # True
8 not in nums # True
~~~

  • Index
    ~~~
    nums = range(1, 10, 2)

nums.index(5) # 2
nums.index(10) # ValueError: 10 is not in list
nums.index(1) # 0
~~~

21
Q

Explain Concatenation and Multiplication in Python?

A

Concatenating strings

In Python, concatenation and multiplication are two operations commonly used with strings and lists to combine or repeat elements. Here’s an explanation of each operation:

Concatenation:
* Concatenation is the process of combining two or more strings or lists into a single string or list.
* In Python, concatenation of strings is performed using the + operator, and concatenation of lists is performed using the + operator as well.
* When concatenating strings, the + operator joins the two strings together, creating a new string that contains the elements of both strings.
* Similarly, when concatenating lists, the + operator merges the two lists, creating a new list that contains the elements of both lists.
* Here are examples of concatenation:
~~~
str1 = “Hello”
str2 = “ World!”
result_str = str1 + str2
print(result_str) # Output: Hello World!

Concatenating lists
list1 = [1, 2, 3]
list2 = [4, 5, 6]
result_list = list1 + list2
print(result_list) # Output: [1, 2, 3, 4, 5, 6]
~~~

Multiplication:
* Multiplication with strings and lists in Python is the process of repeating the elements of the string or list a certain number of times.
* In Python, multiplication with strings is performed using the * operator, and multiplication with lists is also performed using the * operator.
* When multiplying a string by an integer, the * operator duplicates the string the specified number of times.
* Similarly, when multiplying a list by an integer, the * operator replicates the list elements the specified number of times.
* Here are examples of multiplication:
~~~
# Multiplying strings
str1 = “Hello “
result_str = str1 * 3
print(result_str) # Output: Hello Hello Hello

Multiplying lists
list1 = [1, 2]
result_list = list1 * 4
print(result_list) # Output: [1, 2, 1, 2, 1, 2, 1, 2]
~~~

Concatenation and multiplication provide flexible ways to manipulate strings and lists in Python, allowing you to combine or repeat elements to create new sequences or modify existing ones.

Treehouse:
The python docs describe the effects of concatenating and multiplying immutable objects:

Concatenating immutable sequences always results in a new object. This means that building up a sequence by repeated concatenation will have a quadratic runtime cost in the total sequence length. To get a linear runtime cost, you must switch to one of the alternatives below:
* if concatenating str objects, you can build a list and use str.join() at the end or else write to an io.StringIO instance and retrieve its value when complete
* if concatenating bytes objects, you can similarly use bytes.join() or io.BytesIO, or you can do in-place concatenation with a bytearray object. bytearray objects are mutable and have an efficient overallocation mechanism
* if concatenating tuple objects, extend a list instead

This might all sound rather complicated, but the gist is that sometimes new Python sequences are built up by looping over an existing sequence and concatenating each item onto the new sequence. Using a tuple or string for this would be very costly in terms of memory and time!

22
Q

Recap: Sequence Operations Common to All Types

  1. Concatenate
  2. Count
  3. In
  4. Index
  5. Len
  6. Max
  7. Min
  8. Multiply
  9. Not in
  10. Slice

Recap: Mutable Sequence Only Operations
1. Append
2. Del
3. Insert
4. Pop
5. Remove
6. Reverse

A

Recap: Sequence Operations Common to All Types
* 1.Concatenate
Attaches one sequence to the end of another
~~~
nums1 = [1, 2, 3]
nums2 = [4, 5, 6]

nums3 = nums1 + nums2 # [1, 2, 3, 4, 5, 6]
~~~

  • 2.Count
    Returns the number of times an item appears in a sequence
    ~~~
    student_gpas = [2.5, 4.0, 3.2, 2.9, 3.7, 1.5, 4.0]

student_gpas.count(4.0) # 2
~~~

  • 3.In
    Returns boolean indicating whether item is in sequence
    ~~~
    student_gpas = [2.5, 4.0, 3.2, 2.9, 3.7, 1.5, 4.0]

3.2 in student_gpas # True
~~~

  • 4.Index
    Returns index of first occuring passed item
    ~~~
    student_gpas = [2.5, 4.0, 3.2, 2.9, 3.7, 1.5, 4.0]

student_gpas.index(4.0) # 1
~~~

  • 5.Len
    Returns number of items in the sequence
    ~~~
    my_pets = [‘Scofield’, ‘Edel’, ‘Ernie’, ‘Squash’]

len(my_pets) # 4
~~~

  • 6.Max
    Returns largest item in sequence
    ~~~
    student_gpas = [2.5, 4.0, 3.2, 2.9, 3.7, 1.5, 4.0]

max(student_gpas) # 4.0
~~~

  • 7.Min
    Returns smallest item in sequence
    ~~~
    student_gpas = [2.5, 4.0, 3.2, 2.9, 3.7, 1.5, 4.0]

min(student_gpas) # 1.5
~~~

  • 8.Multiply
    Attaches a sequence to itself n number of times
    ~~~
    nums1 = [1, 2, 3]

nums1 * 2 # [1, 2, 3, 1, 2, 3]
~~~

  • 9.Not in
    Returns a boolean indicating whether an item is not in a sequence
    ~~~
    my_pets = [‘Scofield’, ‘Edel’, ‘Ernie’, ‘Squash’]

‘Jellybean’ not in my_pets # True
~~~

  • 10.Slice
    Returns a portion of the original sequence
    ~~~
    student_gpas = [2.5, 4.0, 3.2, 2.9, 3.7, 1.5, 4.0]

student_gpas[1:3] # [4.0, 3.2]
~~~

**Recap: Mutable Sequence Only Operations
**
* 1.Append
Adds an item to the end of a sequence
~~~
my_pets = [‘Scofield’, ‘Edel’, ‘Ernie’, ‘Squash’]

my_pets.append(‘Vera’) # [‘Scofield’, ‘Edel’, ‘Ernie’, ‘Squash’, ‘Vera’]
~~~

  • 2.Del
    Deletes a slice from a sequence
    ~~~
    my_pets = [‘Scofield’, ‘Edel’, ‘Ernie’, ‘Squash’, ‘Vera’]

del my_pets[0:2] # [‘Ernie’, ‘Squash’, ‘Vera’]
~~~

  • 3.Insert
    Inserts an item into a sequence at the provided index
    ~~~
    fruits = [‘apple’, ‘banana’, ‘orange’, ‘pear’, ‘strawberry’]

fruits.insert(2, ‘kiwi’) # [‘apple’, ‘banana’, ‘kiwi’, ‘orange’, ‘pear’, ‘strawberry’]
~~~

  • 4.Pop
    Removes item from sequence, but also retrieves it
    ~~~
    fruits = [‘apple’, ‘banana’, ‘orange’, ‘pear’, ‘strawberry’]

apple = fruits.pop(0) # [‘banana’, ‘orange’, ‘pear’, ‘strawberry’], apple = ‘apple’
~~~

  • 5.Remove
    Removes item first occurrence of item from sequence
    ~~~
    student_gpas = [2.5, 4.0, 3.2, 2.9, 3.7, 1.5, 4.0]

student_gpas.remove(4.0) # [2.5, 3.2, 2.9, 3.7, 1.5, 4.0]
~~~

  • 6.Reverse
    Reverses sequence in place
    ~~~
    my_pets = [‘Ernie’, ‘Squash’, ‘Vera’]

my_pets.reverse() # [‘Vera’, ‘Squash’, ‘Ernie’]
~~~