04. Special sequences ranges, tuples and lists

We've already covered strings, and learned about bytes and bytesarrays in the previous lesson. Now let's dive into the more interesting sequences - ranges, tuples and lists.

1) Ranges

Ranges are a list of integers, usually in a consecutive order. They are most commonly used to initiate and feed values within loops.

Creating a range

There are several options for declaring a range.

range(n)
0 up to but not including m.
range(m,n)
m up to but not including n.
range(m, n, step)
m up to but not including n with increments step.

2) Tuples

Tuples are immutable sequences that can contain any type of element.

Declaring tuples

Tuples are declared with parentheses (()). We can have a one-element tuples such as test,) or an empty tuple (). The comma for one-element tuples is necessary since the parentheses can be interpreted as a mathematical notation.

A simple example of a tuple is the a pair of numbers describing the xy-coordinate system.

given a sequence as an argument, tuple function creates a tuple containing the elements of the sequence

>>> tuple('banana')
('b', 'a', 'n', 'a', 'n', 'a')
>>> tuple(range(2, 10, 2))
(2, 4, 6, 8)

Tuple packing in functions

Since functions may return only one value, it's useful to use tuples when we want to return two or more datasets.

>>> def doubleTwoNumbers(x,y):
...    return (2*x, 2*y)
>>> print(doubleTwoNumbers(4,5))
(8, 10)

Exchanging tuples

You can easily exchange tuples with left, right = right, let. Let's see how we can use tuples to write out the fibonacci sequence.

>>> def fib(n):
...    a,b = 1,1
...    for i in range(n-1):
...        a,b = b,a+b
...    return a
>>> fib(5)
5

3) Lists

Lists are a comma-separated series of mutable values of any type of element. They're like a tuples, but better, with added flexibility.

Lists may contain items of different data types, but usually, they're all of the same type.

Declaring a list

Lists are declared between square brackets ([]).

>>> fruits = ['apple', 'banana', 'pineapple']
>>> print(fruits)
['apple', 'banana', 'pineapple']
>>> min(fruits)
'apple'
>>> 'pineapple' in fruits
True
>>> vegetables = ['kale', 'carrot', 'lettuce']
>>> vegetables + fruits
['kale', 'carrot', 'lettuce', 'apple', 'banana', 'pineapple']

As you can see, you can apply any sequence functions to our lists.

Nesting lists

You may also nest lists to create lists within lists.

>>> nested = [['a', 'b', 'c'], 'c']
>>> nested[0]
['a', 'b', 'c']
>>> nested[1]
'c'

Lists modifications

One unique property of lists is that they are mutable. This means you can change a variable from within the list. Take a look here of the list l and min/max indices i and j.

l[i] = x
Replace value at index i with value x.
l[i:j] = coll
Replace value from i up to but not including j with coll.
l[i:j] = []
Delete values stored from i up to but not including j.
l[i:j:k] = coll
Replace incrementally with step size k.
l[n:n] = coll
Insert elements of coll before the nth element of the list.
l[:] = coll
Replace entire contents of list l with coll.

Delete statement

Another way to remove list items is with the del keyword.

del lst[n]
Remove the nth element from lst.
del lst[i:j]
Remove elements from i through but not including j.
del lst[i:j:k]
Remove every kth element from i up to but not including j.

List modifications

l.extend(L)
Extend the list by appending with collection L.
l.insert(i, x)
Inserts x before the ith element of l.
l.remove(x)
Remove the first occurrence of x.
If x does not exist, an error comes up.
l.append(x)
Append x to the end of l.
l.pop([i])
Remove the ith element and return it.
l.reverse()
Reverses the list.
l.sort()
Sort the list l.

Aching back from coding all day?

Foam Seat Cushion

Aching back from coding all day? Try Back Problems

This foam seat cushion relieves lowerback pain, numbness and pressure sores by promoting healthy weight distribution, posture and spine alignment. Furthermore, it reduces pressure on the tailbone and hip bones while sitting. Perfect for sitting on the computer desk for long periods of time.

$ Check price
99.9599.95Amazon 4.5 logo(9,445+ reviews)

More Back Problems resources

Learn to be a Pythonista!

Programming Python

Learn to be a Pythonista! Try Python

Programming Python shows in-depth tutorials on the language's number of application domains including: system administration, GUIs, the Web, networking, front-end scripting layers, and more. This book focuses on commonly used tools and libraries to give you a comprehensive understanding of Python’s many roles in practical, real-world programming.

$ Check price
64.9964.99Amazon 4 logo(56+ reviews)

More Python resources

Ad