2 Python List, Tuple, Set 05-10-2022
2 Python List, Tuple, Set 05-10-2022
• string_letters = str(letters)
• lists_letters = list(letters)
• tuples_letters = tuple(letters)
• sets_letters = set(letters)
• print("String: ", string_letters)
• print() # for new line
• print("Lists: ", lists_letters)
• print() # for new line
• print("Tuples: ", tuples_letters)
• print() # for new line
• print("Sets: ", sets_letters)
• Allow Duplicates
• Lists allow duplicate values:
thislist =
["apple", "banana", "cherry", "apple", "cher
ry"]
print(thislist)
List Length
• To determine how many items a list has,
use the len() function:
• Example
• Print the number of items in the list:
thislist = ["apple", "banana", "cherry"]
print(len(thislist))
List Items - Data Types
• Example
• Print the second item of the list:
thislist = ["apple", "banana", "cherry"]
print(thislist[1])
Negative Indexing
• Negative indexing means start from the
end
• -1 refers to the last item, -2 refers to the
second last item etc.
• Example
• Print the last item of the list:
thislist = ["apple", "banana", "cherry"]
print(thislist[-1])
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.
• Return the third, fourth, and fifth item:
thislist = ["apple", "banana", "cherry", "orange",
"kiwi", "melon", "mango"]
print(thislist[2:5])
• index 2 (included) and end at index 5 (not
included).
thislist = ["apple", "banana", "cherry",
"orange", "kiwi", "melon", "mango"]
print(thislist[:4]) # from 0th to 3rd
thislist = ["apple", "banana", "cherry",
"orange", "kiwi", "melon", "mango"]
print(thislist[2:]) #from 3rd to end
• Range of Negative Indexes
'cherry']
• thislist =
["apple", "banana", "cherry"]
thislist[1:3] = ["watermelon"]
print(thislist)
['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:
thislist = ["apple", "banana", "cherry"]
thislist.insert(2, "watermelon")
print(thislist)
Append Items
• To add an item to the end of the list, use
the append() method:
• Example
• Using the append() method to append an
item:
• thislist = ["apple", "banana", "cherry"]
• thislist.append("orange")
• print(thislist)
Extend List
• To append elements from another list to
the current list, use the extend() method.
Add the elements of tropical to thislist:
Remove "banana":
• Example
• Delete the entire list:
• cars.sort()
• print(cars)
• prime_numbers = [2, 3, 5, 7]
• # reverse the order of list elements
• prime_numbers.reverse()
• print('Reversed List:', prime_numbers)