1. Traverse the entire list:
Use a for loop to iterate through the list:
magicians = ['alice','david','carolina'] for magician in magicians: print magician
2. Create a list of values
Lists are great for storing collections of numbers.
To create a list of numbers using range(), the result of range() can be directly converted to a list using the function list() as follows:
numbers = list(range(1,6)) print numbers
The result is as follows
[1, 2, 3, 4, 5]
When using the function range(), you can also specify the step size. For example, the following code prints even numbers from 1 to 10:
even_numbers = list(range(2,11,2)) print (even_numbers)
Output result:
[2, 4, 6, 8, 10]
3. Perform simple statistical calculations on lists of numbers
There are several Python functions that specifically work with lists of numbers to find the maximum, minimum and sum of a list of numbers:
digits = [1,2,3,4,5,6,7,8,9,0] print min(digits) print max(digits) print sum(digits)
4. List Comprehension
List comprehension combines the for loop and the code that creates the new element into one line and appends the new element automatically
squares = [value**2 for value in range(1,11)] print (squares)