vertopal.com_lists more working
vertopal.com_lists more working
print(mylist)
# List Items
# List items are ordered, changeable, and allow duplicate values.
# List items are indexed, the first item has index [0], the second
item has index [1]
<class 'list'>
<class 'list'>
banana
cherry
apple
#Negative indexing
#Negative Indexing
#Negative indexing means start from the end
# -1 refers to the last item, -2 refers to the second last item
cherry
# Range of Indexes
# You can specify a range of indexes by specifying where to start and
where to end the range.
# When specifying a range, the return value will be a new list with
the specified items.
# By leaving out the start value, the range will start at the first
item:
#By leaving out the end value, the range will go on to the end of the
list
# This example returns the items from "cherry" to the end:
#This example returns the items from "orange" (-4) to, but NOT
including "mango" (-1):
['apple', 'watermelon']
# Insert Items
# To insert a new list item, without replacing any of the existing
values, we can use the insert() method.
# The insert() method inserts an item at the specified index:
#Append Items
# To add an item to the end of the list, use the append() method
#Extend List ()
# To append elements from another list to the current list, use the
extend() method.
#Remove "banana":
thislist = ["apple", "banana", "cherry"]
thislist.remove("banana")
print(thislist)
['apple', 'cherry']
#If there are more than one item with the specified value, the
remove() method removes the first occurrence
# Remove the first occurrence of "banana":
thislist = ["apple", "banana", "cherry", "banana", "kiwi"]
thislist.remove("banana")
print(thislist)
['apple', 'cherry']
#If you do not specify the index, the pop() method removes the last
item.
#Example: Remove the last item:
thislist = ["apple", "banana", "cherry"]
thislist.pop()
print(thislist)
['apple', 'banana']
['banana', 'cherry']
[]
apple
banana
cherry
#Print all items, using a while loop to go through all the index
numbers
thislist = ["apple", "banana", "cherry"]
i = 0
while i < len(thislist):
print(thislist[i])
i = i + 1
apple
banana
cherry
#Sort Descending
#To sort descending, use the keyword argument reverse = True:
#Example: Sort the list descending:
thislist = ["orange", "mango", "kiwi", "pineapple", "banana"]
thislist.sort(reverse = True)
print(thislist)
#Another way to join two lists is by appending all the items from
list2 into list1, one by one:
#Example: Append list2 into list1:
list1 = ["a", "b" , "c"]
list2 = [1, 2, 3]
for x in list2:
list1.append(x)
print(list1)
#you can use the extend() method, where the purpose is to add elements
from one list to another list:
#Example: Use the extend() method to add list2 at the end of list1:
list1 = ["a", "b" , "c"]
list2 = [1, 2, 3]
list1.extend(list2)
print(list1)