- isinstance(variablename, variabletype)
- Joining or repeating lists (using + or * operators)
- I learnt more list attributes -
- count: number of times elements appear in list
- insert: Insert items into a list
- del: delete a specific List index
- pop: gets and deletes item in list
- remove: delete a specific object from a list
- reverse: to reverse the order of a list
- sort: shuffle items in list
- List index
- An empty list [ ] is False
What I learnt:
1. isinstance(variablename, variabletype)
isinstance() returns True if a specified object is of the specified type, if not, returns False
mystring = 'hello'
myfloat = 10.0
myint = 20
if mystring=='hello':
print(f"String: {mystring}")
if isinstance(myfloat,float) and myfloat==10.0:
print(f"Float: {myfloat}")
if isinstance(myint,int) and myint==20:
print(f"Integer: {myint}")
Output:
String: hello
Float: 10.0
Integer: 20
2. Concatenating (join) using + or repeating lists with *
- Concatenating lists with +
even_numbers = [2,4,6,8] odd_numbers = [1,3,5,7] all_numbers = odd_numbers + even_numbers print(all_numbers)
Output:
[1, 3, 5, 7, 2, 4, 6, 8]
- Repeating list elements in a list with *
print([1,2,3] * 3)
Output:
[1, 2, 3, 1, 2, 3, 1, 2, 3]
3. List Attributes
- list.count(specified_element), list.insert(index_no,element_to_insert)
x = object() y = object() x_list = [x] * 10 y_list = [y] * 10 big_list = x_list + y_list #print variables print(f"x_list contains {len(x_list)} objects") print(f"y_list contains {len(y_list)} objects") print(f"big_list contains {len(x_list)} objects") # testing code if x_list.count(x) == 10 and y_list.count(y) == 10: print("Almost there...") if big_list.count(x) == 10 and big_list.count(y) == 10: print("Great!")
Output:
x_list contains 10 objects y_list contains 10 objects big_list contains 20 objects Almost there... Great!
party_list(1,"Colette")
- del list[index], list.pop(index), list.remove(element_to_remove), list.reverse() or reversed(list), sorted(list) or list.sort()
- .pop() by default removes last item if no index specified, and the item in pop is saved in list.pop()
- Reverse a list:
reversed(list_name)
reversed_list = list_name[::-1]
list_name.reverse() - list.sort()
4. List Index
- list_name[index] to obtain an item in the list at the stated position
- can use negative indexing to get last item(s) in the list
- based on data type of item in the list, can even use attributes
e.g. list_name[index].title() for string items - can replace value in a list_name[index] by assigning new value
5. while [ ] evaluates as False
Thoughts
Today, I learnt many new attributes of lists. Some of the attributes are quite similar to a few string attributes. Knowing these attributes are definitely important when dealing with the various elements in lists.
I’m glad to have learnt how to deal with strings and lists better!