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.
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
Deleting List Elements
Basic List Operations
Built-in List Functions & Methods:
Take a list, say for example this one:
and write a program that prints out all the elements of the list that are less than 5.
- 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.