Python List is a highly flexible and powerful data structure. They are found in other languages, often referred to as arrays. A List is an ordered sequence of information, accessible by index.
In Python, square brackets [ ] indicate a list and individual elements in the list are separated by commas. Here is an example of a list that contains names of friends :
friends = ['hermione', 'Grimoire', 'Harry', 'John'] print(friends)
['hermione', 'Grimoire', 'Harry', 'John']
Changing elements in a list.
The mutability of data_types determines whether you can or cannot change its elements after creating it.
Lists are mutable and assigning to an element at an index, changes the value.
L = [3, 5, 9, 4] L = 0 # L is now [3, 0, 9, 4]
Note that L is now
[3, 0, 9, 4].
Accessing Elements in a List
The first value in the list is at index 0, the second value is at index 1, the third value is at index 2, and so on.
languages = ['python', 'java', 'julia', 'C++']
print(languages) # julia
Indexes can be only integer values, not floats.
Python will give you an
IndexError error message if you use an index that exceeds the number of values in your list value.
print(languages) # IndexError # program output Traceback (most recent call last): File "lists.py", line 3, in <module> print(languages) IndexError: list index out of range
Though indexes start at 0 and go up, you can also use negative integers for the index. The index value -1 refers to the last element in a list, the value -2 refers to the second-to-last element in a list, and so on :
languages = ['python', 'java', 'julia', 'C++'] print(languages[-1]) # C++ print(languages[-2]) # julia
Generating sublists in python | Slicing
Slicing is the process of generating sub-lists from lists via indexes
The first integer in
[1:5] i.e 1 is the index where the slice begins and it ends at the fourth (4) index i.e 5 - 1
Length of a list.
len() function will return the number of values/elements that are in a list passed to it.
L = ['john', 3, 5, 8, True] len(L) # 5
Iterating Over a list
There are many cases in programming that will require you to go over a list or some ordered collection of data.
A simple example is a program that prints every element in a list.
friends = ['john', 'doe', 'harry', 'potter', 'downey'] for f in friends: print(f)
f is a variable, you call it any name. it could be
for friend in friends or
for i in friends.
john doe harry potter downey
Another program example is to calculate the sum of all elements in a list given all its elements are integers or perhaps floats.
figures = [5, 5, 4, 6, 1] sum = 0 for number in figures: sum += number print(sum) # 21
sum is a variable that keeps track of the sum as the loop goes over the list. The last line prints the final sum when the loop is done.