2. Introducing Lists (105m) Flashcards
how do you create lists in python? what will happen if you run bool(list) in python? what does banner = list("welcome")
will do?
To create a list in Python, you can use square brackets [] and separate the items with commas. Here’s an example:
my_list = [1, 2, 3, "four", 5.0]
In this example, we define a list variable called my_list that contains a mix of integer, string, and floating-point values.
If you run bool(my_list) in Python, it will return True if the list is not empty, and False if it is empty. For example:
my_list = [1, 2, 3] print(bool(my_list)) # Output: True my_list = [] print(bool(my_list)) # Output: False
In the first example, my_list is not empty, so bool(my_list) returns True. In the second example, my_list is empty, so bool(my_list) returns False.
Finally, the statement banner = list(“welcome”) will create a list called banner that contains each character in the string “welcome”. The resulting list will contain the characters [‘w’, ‘e’, ‘l’, ‘c’, ‘o’, ‘m’, ‘e’]. In this case, the list() function is used to convert a string into a list of its individual characters.
Create a python code:
1.Create a list called attendees contains “Ken”, “Alena”, “Treasure” as list of items.
2.Output message saying “There are X attendees currently” where X denotes the number of attendees mentioned in the list.
attendees = ["Ken", "Alena", "Treasure"] print("There are", len(attendees), "attendees currently")
Which of the following is mutable: strings, lists, tuples?
In Python, strings and tuples are immutable objects, while lists are mutable objects.
This means that once a string or a tuple is created, its value cannot be changed. If you need to change a string or tuple, you must create a new object with the desired changes.
On the other hand, a list can be modified after it is created. You can add or remove elements from a list, or change the values of its elements.
Here’s an example to illustrate the mutability of lists and the immutability of strings and tuples:
my_string = "hello" my_string[0] = "H" # raises TypeError: 'str' object does not support item assignment my_tuple = (1, 2, 3) my_tuple[0] = 4 # raises TypeError: 'tuple' object does not support item assignment my_list = [1, 2, 3] my_list[0] = 4 # modifies the first element of the list
In this example, we define a string variable called my_string, a tuple variable called my_tuple, and a list variable called my_list. We then try to modify the first character of my_string and the first element of my_tuple, but both of these operations raise a TypeError because strings and tuples are immutable. Finally, we modify the first element of my_list, which works because lists are mutable.
what does append and extend do in lists? how are they used?
In Python, append() and extend() are both list methods that are used to add elements to a list. However, they differ in how they add the elements.
The append() method is used to add a single element to the end of a list. The element to be added is passed as an argument to the append() method. Here’s an example:
~~~
my_list = [1, 2, 3]
my_list.append(4)
print(my_list) # Output: [1, 2, 3, 4]
~~~
In this example, we define a list variable called my_list that contains the values [1, 2, 3]. We then use the append() method to add the value 4 to the end of the list. The resulting list is [1, 2, 3, 4].
The extend() method, on the other hand, is used to add multiple elements to a list. The elements to be added are passed as an iterable (e.g., a list or a tuple) to the extend() method. Here’s an example:
~~~
my_list = [1, 2, 3]
my_list.extend([4, 5, 6])
print(my_list) # Output: [1, 2, 3, 4, 5, 6]
~~~
In this example, we define a list variable called my_list that contains the values [1, 2, 3]. We then use the extend() method to add the values [4, 5, 6] to the end of the list. The resulting list is [1, 2, 3, 4, 5, 6].
In summary, the append() method is used to add a single element to the end of a list, while the extend() method is used to add multiple elements to the end of a list.
To add two lists together, you can simply call the extend() method on the first list and pass the second list as an argument to the method. Here’s an example:
~~~
list1 = [1, 2, 3]
list2 = [4, 5, 6]
list1.extend(list2)
print(list1) # Output: [1, 2, 3, 4, 5, 6]
~~~
How to concat two lists together? (add)
You can concatenate two lists together in Python using the + operator. The + operator is used to combine two lists into a new list. Here’s an example:
list1 = [1, 2, 3] list2 = [4, 5, 6] list3 = list1 + list2 print(list3) # Output: [1, 2, 3, 4, 5, 6]
In this example, we define two lists called list1 and list2. We then use the + operator to concatenate list1 and list2 and create a new list called list3. The resulting list is [1, 2, 3, 4, 5, 6].
Note that when you concatenate two lists using the + operator, the original lists are not modified. Instead, a new list is created that contains the elements of both lists.
Also, keep in mind that you can concatenate more than two lists together by chaining multiple + operators.
How to open interactive REPL?
what does python -i do?
In Python, the -i option when used with the interpreter command (python) launches an interactive session after running the specified script file.
Here’s an example of how to use the -i option:
~~~
$ python -i script.py
~~~
When you run this command, Python will execute the code in script.py and then launch an interactive session. This means that you can access any variables, functions, or objects that were defined in script.py and use them in the interactive session.
The -i option is useful for debugging code or for exploring the state of the program after a script has run. It allows you to inspect variables and objects and to interact with the program in real-time.
Note that if you don’t specify a script file after the -i option, Python will launch an interactive session without executing any code. For example, if you run python -i, you will get an interactive Python shell where you can type in commands and see the results immediately.
In the following code:
books = [ "Automate the Boring Stuff with Python: Practical Programming for Total Beginners - Al Sweigart", "Python for Data Analysis", "Fluent Python: Clear, Concise, and Effective Programming - Luciano Ramalho", "Python for Kids: A Playful Introduction To Programming - Jason R. Briggs", "Hello Web App: Learn How to Build a Web App - Tracy Osborn", ]
What does books[0]
will return and why?
In the given code, books is a list that contains five strings, each representing a book title along with its author name.
When we access books[0]
, it will return the first element of the list, which is the string "Automate the Boring Stuff with Python: Practical Programming for Total Beginners - Al Sweigart"
.
In Python, list indices start from 0. Therefore, books[0]
will always refer to the first element of the list, books[1]
will refer to the second element, and so on.
So in this case, books[0]
will return the first book title from the list, which is “Automate the Boring Stuff with Python: Practical Programming for Total Beginners - Al Sweigart”.
Is list mutable? What is the object within list called? And how will change it?
Yes, lists are mutable objects in Python, which means you can change the values stored in a list after it has been created. This is in contrast to immutable objects, such as strings, where once the object is created, it cannot be changed.
The object within a list in Python is called an element or item. A list can contain elements of any data type, including numbers, strings, other lists, and even objects.
To change an element in a list, you can access it using its index and then assign a new value to it. Here’s an example:
my_list = [1, 2, 3, 4, 5] change the third element of the list (index 2) from 3 to 10 my_list[2] = 10 print(my_list) # Output: [1, 2, 10, 4, 5]
In this example, we first create a list called my_list
with five elements. We then change the third element of the list (which has an index of 2) from the value 3 to the value 10 by using the index operator []
to access the element and then assigning a new value to it. Finally, we print the updated list, which now contains the new value 10 at index 2.
Note that because lists are mutable objects, any changes made to a list will affect the original list object, not just a copy of it.
In the following code:
books = [ "Automate the Boring Stuff with Python: Practical Programming for Total Beginners - Al Sweigart", "Python for Data Analysis", "Fluent Python: Clear, Concise, and Effective Programming - Luciano Ramalho", "Python for Kids: A Playful Introduction To Programming - Jason R. Briggs", "Hello Web App: Learn How to Build a Web App - Tracy Osborn", ]
What does books[-1] and books[-2] will return and why?
In Python, negative indexing is used to access elements from the end of the list. -1 refers to the last element of the list, -2 refers to the second-to-last element, and so on.
So in this case, books[-1]
will return the last book title from the list, which is “Hello Web App: Learn How to Build a Web App - Tracy Osborn”, and books[-2]
will return the second-to-last book title, which is “Python for Kids: A Playful Introduction To Programming - Jason R. Briggs”.
What does this code return? And what it means?
books = [ "Automate the Boring Stuff with Python: Practical Programming for Total Beginners - Al Sweigart", "Python for Data Analysis - Wes Mckinney", "Fluent Python: Clear, Concise, and Effective Programming - Luciano Ramalho", "Python for Kids: A Playful Introduction To Programming - Jason R. Briggs", "Hello Web App: Learn How to Build a Web App - Tracy Osborn", ] books[len(books) -1]
The given code returns the last element of the books list, which is the string "Hello Web App: Learn How to Build a Web App - Tracy Osborn"
.
Here’s how the code works:
len(books)
returns the length of the books list, which is 5.
We subtract 1 from the length of the list using len(books) - 1
to get the index of the last element of the list. In Python, list indexing starts from 0, so the last element of the list is at index 4.
Finally, we use the calculated index (len(books) - 1)
to access the last element of the books list using square bracket notation ([])
.
Therefore, books[len(books) - 1]
returns the last element of the books list, which is "Hello Web App: Learn How to Build a Web App - Tracy Osborn"
.
what is insert() method and how will you use it?
The insert()
method is a built-in method of Python lists that allows you to insert an element at a specific index in the list. The insert()
method takes two arguments: the index at which to insert the new element, and the element itself.
Here is the syntax for the insert() method:
~~~
list_name.insert(index, element)
~~~
The index argument is the position at which to insert the new element, and element is the object to be inserted.
Here’s an example of how to use the insert()
method to insert a new element into a list:
my_list = [1, 2, 3, 4] Insert the value 5 at index 2 my_list.insert(2, 5) print(my_list) # Output: [1, 2, 5, 3, 4]
In this example, we first create a list called my_list with four elements. We then use the insert()
method to insert the value 5 at index 2 in the list. The resulting list is [1, 2, 5, 3, 4]
.
Note that if the index specified in the insert()
method is greater than the length of the list, the new element will be inserted at the end of the list. If the index is negative, it will count from the end of the list. For example, my_list.insert(-1, 6)
will insert the value 6 at the second-to-last position in the list.
Also note that the insert()
method modifies the original list in place, and it does not return a new list.
Explain this code:
books = [ "Automate the Boring Stuff with Python: Practical Programming for Total Beginners - Al Sweigart", "Python for Data Analysis - Wes Mckinney", "Fluent Python: Clear, Concise, and Effective Programming - Luciano Ramalho", "Python for Kids: A Playful Introduction To Programming - Jason R. Briggs", "Hello Web App: Learn How to Build a Web App - Tracy Osborn", ] print("Suggested Gift: {}".format(books[0])) books.insert(0, "Learning Python: Powerful Object-Oriented Programming") books[0] += " - Mark Lutz"
The given code defines a list called books, which contains five strings, each representing a book title along with its author name. It then prints a message with the suggested gift, which is the first book title in the list.
print("Suggested Gift: {}".format(books[0]))
The output of this code will be:
~~~
Suggested Gift: Automate the Boring Stuff with Python: Practical Programming for Total Beginners - Al Sweigart
~~~
After printing the suggested gift, the code inserts a new book title at the beginning of the list using the insert() method:
~~~
books.insert(0, “Learning Python: Powerful Object-Oriented Programming”)
~~~
This inserts a new book title “Learning Python: Powerful Object-Oriented Programming” at index 0 of the books list.
Finally, the code modifies the first element of the books list by adding the name of the author of the book using string concatenation:
~~~
books[0] += “ - Mark Lutz”
~~~
This concatenates the author’s name “ - Mark Lutz” to the first book title “Learning Python: Powerful Object-Oriented Programming”. The resulting string becomes “Learning Python: Powerful Object-Oriented Programming - Mark Lutz”.
The final books list after these operations will look like:
~~~
[ “Learning Python: Powerful Object-Oriented Programming - Mark Lutz”, “Automate the Boring Stuff with Python: Practical Programming for Total Beginners - Al Sweigart”, “Python for Data Analysis - Wes Mckinney”, “Fluent Python: Clear, Concise, and Effective Programming - Luciano Ramalho”, “Python for Kids: A Playful Introduction To Programming - Jason R. Briggs”, “Hello Web App: Learn How to Build a Web App - Tracy Osborn”]
~~~
So the code essentially adds a new book title at the beginning of the list, and then modifies the first book title by adding the author’s name to it.
What is the difference between insert method and append method in lists?
In Python, both insert() and append() are methods of lists that are used to add elements to a list. However, they work differently:
- append() is used to add an element to the end of a list.
- insert() is used to add an element to a specific position in a list, by specifying the index where the element should be inserted.
Here’s an example that shows the difference between append() and insert():
~~~
my_list = [1, 2, 3, 4]
Append 5 to the end of the list
my_list.append(5)
print(my_list) # Output: [1, 2, 3, 4, 5]
Insert 6 at index 2
my_list.insert(2, 6)
print(my_list) # Output: [1, 2, 6, 3, 4, 5]
~~~
In this example, we first create a list called my_list with four elements. We then use the append()
method to add the value 5 to the end of the list. The resulting list is [1, 2, 3, 4, 5]
.
Next, we use the insert()
method to add the value 6 at index 2 in the list. The resulting list is [1, 2, 6, 3, 4, 5]
.
So, the main difference between insert() and append() is that insert() allows you to specify the position where you want to add the element, while append() always adds the element to the end of the list.
how to insert and delete items in lists?
To insert an item in a list, you can use the insert() method of the list. The insert() method takes two arguments: the index where you want to insert the item and the item itself.
Here’s an example of how to use the insert() method to insert an item in a list:
~~~
my_list = [1, 2, 3, 4]
Insert 5 at index 2
my_list.insert(2, 5)
print(my_list) # Output: [1, 2, 5, 3, 4]
~~~
To delete an item from a list, you can use the del statement or the pop() method of the list.
To delete an item using the del statement, you need to specify the index of the item you want to delete. Here’s an example:
~~~
my_list = [1, 2, 3, 4]
Delete item at index 2
del my_list[2]
print(my_list) # Output: [1, 2, 4]
~~~
Alternatively, you can use the pop() method to remove and return the item at a specific index. If you don’t specify an index, the last item in the list will be removed. Here’s an example:
~~~
my_list = [1, 2, 3, 4]
Remove item at index 2
item = my_list.pop(2)
print(my_list) # Output: [1, 2, 4]
print(item) # Output: 3
~~~
In this example, we use the pop() method to remove the item at index 2, which is 3. The method returns the removed item, which we store in the item variable. The resulting list is [1, 2, 4].
Note that both the del statement and the pop() method modify the list in place, so the original list will be changed after the item is removed.
What does this code show?craigs_lunch = "\N{TACO}"
The given code assigns the Unicode character “\N{TACO}” to a variable named craigs_lunch
.
The Unicode character “\N{TACO}” represents a taco icon, and it can be used in Python strings, among other places. When the variable craigs_lunch
is used in a string, it will be replaced with the taco icon.
Here’s an example of how to use the variable craigs_lunch
to create a string with a taco icon:
~~~
my_string = “Today’s lunch: {}”.format(craigs_lunch)
print(my_string) # Output: “Today’s lunch: 🌮”
~~~
In this example, we create a new string called my_string
that includes the taco icon by using the format() method to insert the craigs_lunch
variable into the string. When we print my_string
, it will display the message “Today’s lunch: 🌮”, where the taco icon is displayed instead of the craigs_lunch variable.
What does books.pop() do?
The pop() method is a built-in method of Python lists that removes and returns the last element from a list. If you specify an index as an argument, it will remove and return the element at that index.
In the case of books.pop(), the method will remove and return the last element from the books list.
Here’s an example to demonstrate how the pop() method works:
~~~
my_list = [1, 2, 3, 4]
Remove and return the last element
last_element = my_list.pop()
print(my_list) # Output: [1, 2, 3]
print(last_element) # Output: 4
~~~
In this example, we first create a list called my_list with four elements. We then use the pop() method without an argument to remove and return the last element from the list, which is 4. We store the removed element in a variable called last_element.
After the pop() method is called, the my_list list is updated to [1, 2, 3], with the last element 4 removed.
So, in the case of books.pop(), it will remove and return the last book title from the books list. If you want to remove an element from a specific index in the list, you can pass the index as an argument to the pop() method, like books.pop(1) to remove and return the book title at index 1.