popolo - code simple..

popolo - code simple..

Python Basics - Working with Lists

Python Basics - Working with Lists

Theodoros Kafantaris's photo
Theodoros Kafantaris
·Apr 24, 2022·

7 min read

In this article, we will discuss with more details about lists. Lists allow us to store sets of information in one place, whether we have just a few items or millions of items. Lists are one of Python’s most powerful features readily accessible to new programmers, and they tie together many important concepts in programming.

What Is a List?

A list is a collection of items in a particular order. We can make a list that includes the letters of the alphabet, the digits from 0–9, or the names of all the people in our family. We can put anything we want into a list, and the items in our list don’t have to be related in any particular way. Because a list usually contains more than one element, it’s a good idea to make the name of our list plural, such as letters, digits, or fruits.

>>> fruits=['apple','orange','lemon']
>>> print(fruits)
['apple', 'orange', 'lemon']

Accessing Elements in a List

Lists are ordered collections, so we can access any element in a list by telling Python the position, or index, of the item desired. To access an element in a list, write the name of the list followed by the index of the item enclosed in square brackets.

>>> fruits=['apple','orange','lemon']
>>> print(fruits[0])
apple
>>> print(fruits[1])
orange
>>> print(fruits[2])

Index Positions Start at 0, Not 1

Python considers the first item in a list to be at position 0, not position 1. This is true of most programming languages, and the reason has to do with how the list operations are implemented at a lower level. If we’re receiving unexpected results, determine whether we are making a simple off-by-one error.

Modifying Elements in a List

The syntax for modifying an element is similar to the syntax for accessing an element in a list. To change an element, use the name of the list followed by the index of the element we want to change, and then provide the new value we want that item to have.

>>> fruits=['apple','orange','lemon']
>>> fruits[0]='banana'
>>> print(fruits)
['banana', 'orange', 'lemon']

Appending Elements to the End of a List

The simplest way to add a new element to a list is to append the item to the list. When we append an item to a list, the new element is added to the end of the list. Using the same list we had in the previous example, we’ll add the new element 'kiwi' to the end of the list:

>>> fruits.append('kiwi')
>>> print(fruits)
['banana', 'orange', 'lemon', 'kiwi']

Inserting Elements into a List

We can add a new element at any position in our list by using the insert() method. We do this by specifying the index of the new element and the value of the new item.

>>> fruits=['apple','orange','lemon']
>>> fruits.insert(1,'kiwi')
>>> print(fruits)
['apple', 'kiwi', 'orange', 'lemon']

Removing an Item Using the del Statement

If we know the position of the item we want to remove from a list, we can use the del statement.

>>> fruits=['apple','orange','lemon']
>>> del fruits[2]
>>> print(fruits)
['apple', 'orange']

Removing an Item Using the pop() Method

Sometimes we’ll want to use the value of an item after we remove it from a list. For example, in a web application, we might want to remove a user from a list of active members and then add that user to a list of inactive members.

The pop() method removes the last item in a list, but it lets we work with that item after removing it. The term pop comes from thinking of a list as a stack of items and popping one item off the top of the stack. In this analogy, the top of a stack corresponds to the end of a list.

>>> fruits=['apple','orange','lemon']
>>> popped_fruit=fruits.pop()
>>> print(fruits)
['apple', 'orange']
>>> print(popped_fruit)
lemon

Popping Items from any Position in a List

We can use pop() to remove an item from any position in a list by including the index of the item we want to remove in parentheses.

>>> fruits=['apple','orange','lemon']
>>> first_fruit=fruits.pop(0)
>>> print(fruits)
['orange', 'lemon']
>>> print(first_fruit)
apple

Removing an Item by Value

Sometimes we won’t know the position of the value you want to remove from a list. If we only know the value of the item we want to remove, we can use the remove() method.

>>> fruits=['apple','orange','lemon']
>>> fruits.remove('orange')
>>> print(fruits)
['apple', 'lemon']

The remove() method deletes only the first occurrence of the value you specify. If there’s a possibility the value appears more than once in the list, you’ll need to use a loop to make sure all occurrences of the value are removed.

Sorting a List Permanently with the sort() Method

Python’s sort() method makes it relatively easy to sort a list. Imagine we have a list of fruits and want to change the order of the list to store them alphabetically. To keep the task simple, let’s assume that all the values in the list are lowercase.

>>> fruits=['apple','orange','lemon']
>>> fruits.sort()   
>>> print(fruits)
['apple', 'lemon', 'orange']

Sorting a List Temporarily with the sorted() Function

To maintain the original order of a list but present it in a sorted order, we can use the sorted() function. The sorted() function lets us display our list in a particular order but doesn’t affect the actual order of the list.

>>> fruits=['apple','orange','lemon']
>>> print(sorted(fruits))
['apple', 'lemon', 'orange']
>>> print(fruits)
['apple', 'orange', 'lemon']

Printing a List in Reverse Order

To reverse the original order of a list, we can use the reverse() method. If we originally stored the list of fruits in chronological order according to when we owned them, we could easily rearrange the list into reverse chronological order:

>>> fruits=['apple','orange','lemon']
>>> fruits.reverse()
>>> print(fruits)
['lemon', 'orange', 'apple']

Notice that reverse() doesn’t sort backward alphabetically; it simply reverses the order of the list.

Finding the Length of a List

We can quickly find the length of a list by using the len() function. The list in this example has three items:

>>> fruits=['apple','orange','lemon']
>>> len(fruits)
3

Looping Through an Entire List

We will often want to run through all entries in a list, performing the same task with each item. When you want to do the same action with every item in a list, you can use Python’s for loop.

Let’s use a for loop to print out each name in a list of fruits:

>>> fruits=['apple','orange','lemon']
>>> for fruit in fruits:
...  print(fruit)

apple
orange
lemon

Doing More Work Within a for Loop

We can do just about anything with each item in a for loop. Let’s build on the previous example by printing a message for each fruit:

>>> fruits=['apple','orange','lemon']
>>> for fruit in fruits:
...  print(f"My favorite fruit is {fruit.title()}!")
... 
My favorite fruit is Apple!
My favorite fruit is Orange!
My favorite fruit is Lemon!

Using the range() Function

Python’s range() function makes it easy to generate a series of numbers. For example, we can use the range() function to print a series of numbers like this:

>>> for value in range(1, 5):
...     print(value)
... 
1
2
3
4

Using range() to Make a List of Numbers

If we want to make a list of numbers, we can convert the results of range() directly into a list using the list() function. When we wrap list() around a call to the range() function, the output will be a list of numbers.

>>> numbers = list(range(1, 6))
>>> print(numbers)
[1, 2, 3, 4, 5]

Simple Statistics with a List of Numbers

A few Python functions are helpful when working with lists of numbers. For example, we can easily find the minimum, maximum, and sum of a list of numbers:

digits = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]
>>> min(digits)
0
>>> max(digits)
9
>>> sum(digits)
45

Slicing a List

To make a slice, we specify the index of the first and last elements we want to work with. As with the range() function, Python stops one item before the second index we specify. To output the first three elements in a list, we would request indices 0 through 2, which would return elements 0 and 1.

fruits=['apple','orange','lemon','kiwi','peach']
>>> print(fruits[0:2])
['apple', 'orange']
 
Share this