09/05/2020
The item at a certain index in a list can be reassigned.
For example:
----------Program--------
nums = [7, 7, 7, 7, 7]
nums[2] = 5
print(nums)
----------OUTPUT----------
[7, 7, 5, 7, 7]
Lists can be added and multiplied in the same way as strings.
For example:
----------Program--------
nums = [1, 2, 3]
print(nums + [4, 5, 6])
print(nums * 3)
----------OUTPUT----------
[1, 2, 3, 4, 5, 6]
[1, 2, 3, 1, 2, 3, 1, 2, 3]
Lists and strings are similar in many ways - strings can be thought of as lists of characters that can't be changed.
To check if an item is in a list, the in operator can be used. It returns True if the item occurs one or more times in the list, and False if it doesn't.
----------Program--------
words = ["spam", "egg", "spam", "sausage"]
print("spam" in words)
print("egg" in words)
print("tomato" in words)
----------OUTPUT----------
True
True
False
The in operator is also used to determine whether or not a string is a substring of another string.
To check if an item is not in a list, you can use the not operator in one of the following ways:
----------Program--------
nums = [1, 2, 3]
print(not 4 in nums)
print(4 not in nums)
print(not 3 in nums)
print(3 not in nums)
----------OUTPUT----------
True
True
False
False
Another way of altering lists is using the append method. This adds an item to the end of an existing list. The dot before append is there because it is a method of the list class. Methods will be explained in a later lesson.
----------Program----------
nums = [1, 2, 3]
nums.append(4)
print(nums)
----------OUTPUT----------
[1, 2, 3, 4]
To get the number of items in a list, you can use the len function. Unlike append, len is a normal function, rather than a method. This means it is written before the list it is being called on, without a dot.
----------Program---------
nums = [1, 3, 5, 2, 4]
print(len(nums))
----------OUTPUT----------
5
The insert method is similar to append, except that it allows you to insert a new item at any position in the list, as opposed to just at the end.
----------Program---------
words = ["Python", "fun"]
index = 1
words.insert(index, "is")
print(words)
----------OUTPUT----------
['Python', 'is', 'fun']
The index method finds the first occurrence of a list item and returns its index.
If the item isn't in the list, it raises a ValueError.
----------Program---------
letters = ['p', 'q', 'r', 's', 'p', 'u']
print(letters.index('r'))
print(letters.index('p'))
print(letters.index('z'))
----------OUTPUT----------
2
0
ValueError: 'z' is not in list
There are a few more useful functions and methods for lists.
max(list): Returns the list item with the maximum value
min(list): Returns the list item with minimum value
list.count(obj): Returns a count of how many times an item occurs in a list
list.remove(obj): Removes an object from a list
list.reverse(): Reverses objects in a list
For list basics https://www.facebook.com/114683366580248/posts/259182268797023/