Sequence
The most basic data structure in Python is the sequence (lists, tuples and strings). Every element in a sequence is assigned a number, which is its position or index. The first index is always zero, the second is one, and so forth.
Indexes are numbered from 0 to n-1 where n is the number of items (or characters):
H e l l o , _ w o r l d !
0 1 2 3 4 5 6 7 8 9 10 11 12
There are certain things you can do with all sequence types. These operations include indexing, slicing, adding, multiplying, and checking for membership.
Python Lists
The list is versatile data structure that is available in Python, it is a mutable data structure, which can be written as a list of comma-separated values (items) between square brackets.
An Important thing to note about a list is that items in a list need not be of the same type.
Creating a list is as simple as putting different comma-separated values between square brackets. For example −
list1 = ['physics', 'chemistry', 1997, 2000];
list2 = [1, 2, 3, 4, 5 ];
list3 = ["a", "b", "c", "d"]
Similar to string indices, list indices start at 0, and lists can be sliced, concatenated and so on.
Click on the link below to go through a python tutorial on lists. By the end you should have a basic understanding of:
Accessing Values in Lists
Updating Lists
Deleting List Elements
Basic List Operations
Built-in List Functions & Methods:
Exercises
Take a list, say for example this one:
a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
and write a program that prints out all the elements of the list that are less than 5.
Extension questions:
- Instead of printing the elements one by one, make a new list that has all the elements less than 5 from this list in it and print out this new list.
- Ask the user for a number and return a list that contains only elements from the original list 'a' that are smaller than that number given by the user.
- Write this in one line of Python. (Requires 'List comprehension')
Click the button below for a sample solution that solves the exercise, including extras 1 and 2.
a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
num = int(input("Choose a number: "))
new_list = []
for i in a:
if i < num:
new_list.append(i)
print (new_list)