Lists are collections of ordered elements. We can define lists using square brackets. The elements a list contains don't have to all be of the same type.
fruits = ['apple', 'banana', 'peach', 'pear']
nums = [4, 56, 73, 12]
mixed = [3, 'red', 45.012, [3, 5]] # lists can even contain other lists!We can check if a list contains an element using 'in':
fruits = ['apples', 'bananas', 'pears']
if 'apples' in fruits:
print('true!')We can use == and != with lists.
fruits1 = ['apples', 'bananas']
fruits2 = ['pears', 'cherries']
print(fruits1 == fruits2) # False
print(fruits1 != fruits2) # TrueAccess lists by index, note that indexes start at 0. You can also access them negatively
nums = [4, 56, 73, 12]
print(nums[0])
print(nums[2])
>>> 4
>>> 73
print(nums[-1])
print(nums[-3])
>>> 12
>>> 56You can also access lists using colons ([::]), this is called slicing! The value before the first colon is the steps you want to take, the second value is the subset of string you may want to take, and the third value is the reverse step. Note that you cannot use the first and third values at the same time (no such thing as simultaneous forward and backward stepping).
nums = [4, 56, 73, 12, 17, 99, 42, 87]
print(nums)
print(nums[2::])
print(nums[:2:])
print(nums[::-1])
print(nums[2:4:])
print(nums[:6:-1])
print(nums[2:6:-1])
print(nums[::-2])
>>> [4, 56, 73, 12, 17, 99, 42, 87]
>>> [73, 12, 17, 99, 42, 87]
>>> [4, 56]
>>> [87, 42, 99, 17, 12, 73, 56, 4]
>>> [73, 12]
>>> [87]
>>> []
>>> [87, 99, 12, 56]copy()creates a copy of the listappend()appends an element to the endinsert()inserts the value at the specified indexremove()removes the first occurance of the elementpop()removes the element at the given indexextend()combines two lists into oneindex()returns the index of a given elementreverse()reverses a listsort()sorts a list
reversed(seq)returns a reversed object when given an iterable, should be typecasted to list for further usagesorted(seq)returns a new sorted list when given an unsorted iterable, unlikereversed(seq)it does not need typecasting
seqString = 'Python'
print(reversed(seqString))
print(list(reversed(seqString)))
print(list(sorted(seqString)))
print(sorted(seqString))
>>> <reversed object at 0x7fb67b77dd68>
>>> ['n', 'o', 'h', 't', 'y', 'P'] #List typecasted reversed object
>>> ['P', 'h', 'n', 'o', 't', 'y']
>>> ['P', 'h', 'n', 'o', 't', 'y'] #Same as the non typecasted versionTuples are like lists, but immutable. Their literals are surrounded by parentheses (). For more info, check out the official docs.
Single item tuples need a trailing comma to distinguish them from grouping parentheses. Empty tuples are created using tuple().
('David', '503-555-9895')
(2016, 7, 13)
('Alice', )
tuple()Why use tuples over lists? Lists tend to be used for homogenous data, tuples tend to be used for "pairs", "triplets" or "n-tuples"; groupings of heterogenous data. For example, a list of friends is a list because it doesn't matter exactly how many there are and all are names. A pair of address and phone number would be a tuple, since each is interpreted differently and if there was another item, it you wouldn't know what to do with it.
friend_names = ['Kate', 'Al']
contact_info = ('123 Main St', '503-555-1234')You can cast a sequence to a tuple with the tuple() function.
fruits = ['apples', 'bananas', 'pears']
fruits_tuple = tuple(fruits)
print(fruits_tuple)Tuples are immutable. Trying to modify them is an exception.
contact_info = ('123 Main St', '503-555-1234')
contact_info[0] = '456 Water Ave' # Throws TypeErrorAlso, realize there are four different ways to use parentheses now:
- Order of operations
- Line continuations
- Function calls
- Tuple literals
x = (4 + 3) * 6
x = (4 *
3 *
8)
min(5, 6)
('Al', 'Kate')You can also 'pack' a tuple into an other variable, and 'unpack' it into an other set of variables.
x = ("Mr. Python", 30, "Java(script)") # tuple packing
(name, age, fav_drink) = x # tuple unpacking
print(name)
print(age)
print(fav_drink)
>>> Mr. Python
>>> 30
>>> Java(script)