In this blog you’ll learn how to loop through an entire
list using just a few lines of code regardless of how
long the list is. Looping allows you to take the same action, or set of actions,
with every item in a list. As a result, you’ll be able to work efficiently with
lists, slice them as per need and also learn about tuples.
Looping Through an Entire List
When you want to do the same action with every item in a list, you can
use Python’s for loop. Let’s say we have a list of different foods’ names, and we want to print out
each name in the list. We could do this by retrieving each name from the
list individually, but this approach could cause several problems. For one,
it would be repetitive to do this with a long list of names. Also, we’d have to
change our code each time the list’s length changed. A for loop avoids both
of these issues by letting Python manage these issues internally.
foods = ['rice', 'pizza', 'pasta', 'bread']
for food in foods:
print(food)
A Closer Look at Looping
The concept of looping is important because it’s one of the most common
ways a computer automates repetitive tasks. When you’re using loops for the first time, keep in mind that the set of
steps is repeated once for each item in the list, no matter how many items
are in the list. If you have a million items in your list, Python repeats these
steps a million times—and usually very quickly.
Doing Something Within and After a for Loop
foods = ['rice', 'pizza', 'pasta', 'bread']
for food in foods:
print(food.title() + " is a great food.")
print("Which food do you like the most?")
Avoiding Indentation Errors
Python uses indentation to determine when one line of code is connected to
the line above it. In the previous examples, the lines that printed messages to
individual magicians were part of the for loop because they were indented.
Python’s use of indentation makes code very easy to read. Basically, it uses
whitespace to force you to write neatly formatted code with a clear visual
structure. In longer Python programs, you’ll notice blocks of code indented
at a few different levels. These indentation levels help you gain a general
sense of the overall program’s organization.
Let’s examine some of the more common indentation errors.
Forgetting to Indent
foods = ['rice', 'pizza', 'pasta', 'bread']
for food in foods:
print(food.title() + " is a great food.")
Indenting Unnecessarily
message = "Hello Python world!"
print(message)
Forgetting the Colon
foods = ['rice', 'pizza', 'pasta', 'bread']
for food in foods
print(food.title() + " is a great food.")
Making Numerical Lists
Lists are ideal for storing sets of numbers, and Python provides a number of tools to help you work efficiently with lists of numbers.
Using the range() Function
Python’s range() function makes it easy to generate a series of numbers.
For example, you can use the range() function to print a series of numbers
like this:
for value in range(1,5):
print(value)
In this example, range() prints only the numbers 1 through 4. This is
another result of the off-by-one behavior you’ll see often in programming
languages. The range() function causes Python to start counting at the first
value you give it, and it stops when it reaches the second value you provide.
Because it stops at that second value, the output never contains the end
value, which would have been 5 in this case. Here to print the numbers from 1 to 5, you would use range(1,6).
Using range() to Make a List of Numbers
If you want to make a list of numbers, you can convert the results of range()
directly into a list using the list() function. When you wrap list() around a
call to the range() function, the output will be a list of numbers.
numbers = list(range(1,6))
print(numbers) gives [1, 2, 3, 4, 5]
We can also use the range() function to tell Python to skip numbers
in a given range. For example, here’s how we would list the even numbers
between 1 and 10:
even_numbers = list(range(2,11,2))
print(even_numbers) gives [2, 4, 6, 8, 10]
For example, let's make a list of squares of above even numbers.
even_squares = []
for even_number in list(range(2,11,2)):
even_squares.append(even_number**2)
print(even_squares) gives [4,16,36,64,100]
Simple Statistics with a List of Numbers
A few Python functions are specific to lists of numbers. For example, you
can easily find the minimum, maximum, and sum of a list of numbers:
digits = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]
print(min(digits)) gives 0
print(max(digits)) gives 9
print(sum(digits)) gives 45
List Comprehensions
The approach described earlier for generating the list squares consisted of
using three or four lines of code. A list comprehension allows you to generate
this same list in just one line of code. A list comprehension combines the
for loop and the creation of new elements into one line, and automatically
appends each new element.
The following example builds the same list of square numbers you saw
earlier but uses a list comprehension:
even_squares = [value**2 for value in range(2,11,2)]
print(even_squares) gives [4,16,36,64,100]
To use this syntax, begin with a descriptive name for the list, such as even_squares. Next, open a set of square brackets and define the expression for
the values you want to store in the new list. In this example the expression is value**2, which raises the value to the second power. Then, write
a for loop to generate the numbers you want to feed into the expression,
and close the square brackets. Notice that no colon is used at the end of the for statement.
Working with Part of a List
Slicing a List
To make a slice, you specify the index of the first and last elements you
want to work with. As with the range() function, Python stops one item
before the second index you specify.
players = ['charles', 'martina', 'michael', 'florence', 'eli']
print(players[1:4]) gives ['martina', 'michael', 'florence']
If you omit the first index in a slice, Python automatically starts your
slice at the beginning of the list:
print(players[:4]) gives ['charles', 'martina', 'michael', 'florence']
If you omit the last index in a slice, Python automatically slices upto the ending of the list:
print(players[2:]) gives ['michael', 'florence', 'eli']
This syntax allows you to output all of the elements from any point in
your list to the end regardless of the length of the list. Recall that a negative index returns an element a certain distance from the end of a list;
therefore, you can output any slice from the end of a list.
For example, if
we want to output the last three players on the roster, we can use the slice
players[-3:]:
print(players[-3:]) gives ['michael', 'florence', 'eli']
This prints the names of the last three players and would continue to
work as the list of players changes in size.
Looping Through a Slice
You can use a slice in a for loop if you want to loop through a subset of
the elements in a list. In the next example we loop through the first three
players and print their names as part of a simple roster:
players = ['charles', 'martina', 'michael', 'florence', 'eli']
print("Here are the first three players on my team:")
for player in players[:3]:
print(player.title())
Copying a List
Often, you’ll want to start with an existing list and make an entirely new list
based on the first one. Many programmer face some issues while copying a list, we will learn to avoid it. First let's do it the intuitive but wrong way.
my_foods = ['pizza', 'carrot cake']
friend_foods = my_foods
my_foods.append('burger')
friend_foods.append('pasta')
print(my_foods) gives ['pizza', 'carrot cake', 'burger', 'pasta']
print(friend_foods) gives ['pizza', 'carrot cake', 'burger', 'pasta']
Here both burger and pasta is added to both lists but we wanted to treat it individually.
The right way is:
my_foods = ['pizza', 'carrot cake']
friend_foods = my_foods[:]
my_foods.append('burger')
friend_foods.append('pasta')
print(my_foods) gives ['pizza', 'carrot cake', 'burger']
print(friend_foods) gives ['pizza', 'carrot cake', 'pasta']
Tuples
Lists work well for storing sets of items that can change throughout the
life of a program. The ability to modify lists is particularly important when
you’re working with a list of users on a website or a list of characters in a
game. However, sometimes you’ll want to create a list of items that cannot
change. Tuples allow you to do just that. Python refers to values that cannot
change as immutable, and an immutable list is called a tuple.
Defining a Tuple
A tuple looks just like a list except you use parentheses instead of square
brackets. Once you define a tuple, you can access individual elements by
using each item’s index, just as you would for a list.
dimensions = (200, 50)
print(dimensions[0]) gives 200
for dimension in dimensions:
print(dimension)
You will get an error if you try to run code below as the elements of tuple cannot be changed.
dimensions[0] = 300
Although you can’t modify a tuple, you can assign a new value to a variable
that holds a tuple. So if we wanted to change our dimensions, we could
redefine the entire tuple:
dimensions = (200, 50)
print(dimensions) gives (200, 50)
dimensions = (400, 100)
print(dimensions) gives (400, 100)
Conclusion
In this blog you learned how to work efficiently with the elements in a
list. You learned how to work through a list using a for loop, how Python
uses indentation to structure a program, and how to avoid some common
indentation errors. You learned to make simple numerical lists, as well as a
few operations you can perform on numerical lists. You learned how to slice
a list to work with a subset of items and how to copy lists properly using a
slice. You also learned about tuples, which provide a degree of protection
to a set of values that shouldn’t change.
Post a Comment
Let's make it better!
Comment your thoughts...