Quantcast
Channel: Planet Python
Viewing all articles
Browse latest Browse all 22851

Python for Beginners: Python Lists Cheat Sheet

$
0
0

What is a List?

Python Lists are used to store collections of data. Python can assign multiple values to a single list, which is handy if you’re dealing with a lot of data.

Lists can hold any type of data, including integers, strings, and even other lists. Lists are dynamic and can be changed. Using special methods, we can add or remove items from a Python list.

The elements in a list are indexed, with each having its definite place in the order of the list. Unlike Python strings, the contents of a list can be changed.

List Creation

Python lists are written using square brackets. The elements inside the list are separated by commas. Later, we’ll see how to add and remove elements.

# a list for days of the work week
weekdays = ["Monday","Tuesday","Wednesday","Thursday","Friday"]

# an empty list just waiting to do something
empty_list = []

# lists can hold data of different types
mix_list = ["one","two",1,2]

Finding the Length of a List

Find the length of a list using the len() method. This method will return the total number of elements in the list.

nums = [0,1,2,3,4,5,6,7,8,9]
# print the total number of items in the list
print("Length of the list: ", len(nums))

Output

Length of the list:  10

Appending a List

We can add items to a list using the append() method. The new element will appear at the end of the list.

# a list of popular car manufacturers
car_brands = ["BMW","Ford","Toyota","GM","Honda","Chevrolet"]

# add to a list with append()
car_brands.append("Tesla")

List Insert

In the above example, we saw that we could add items to the end of a list. What if we wanted to put something at the beginning, or even the middle?

With the insert() method, we can specify where in the list to add a new element.

letters = ['B','C','D','E','F','G']
letters.insert(0,'A') # add element 'A' at the first index

print(letters)

Output

['A', 'B', 'C', 'D', 'E', 'F', 'G']

List Insert Syntax:

my_list.insert(x,y) # this will insert y before x
# an example of inserting an element into the third position in a list
top_five = ["The Beatles","Marvin Gaye","Gorillaz","Cat Power"]
top_five.insert(2, "Prince")

print(top_five)

Output

['The Beatles', 'Marvin Gaye', 'Prince', 'Nirvana', 'Cat Power']

Removing elements from a List

To remove an element from a list, using the remove() method. This method will find the first occurrence of an item in a list and delete it.

# a basic to do list
to_do = ["dishes","laundry","dusting","feed the dog"]
# we already fed Fido!
to_do.remove("feed the dog")
print("Things to do: ", to_do)

# remove the first 3 in the list
nums = [1,2,3,3,4,5]
nums.remove(3)
print(nums)

Output

Things to do:  ['dishes', 'laundry', 'dusting']
[1, 2, 3, 4, 5]

Suggested reading: How to make a chat app in Python?

Extending Lists

Python provides a way of joining lists with the extend() method. Using this method, the elements of one list will be added to the end of another.

# we need a list of items to send to the  movers
furniture = ["bed","chair","bookcase"]

# add additional elements with extend()
furniture.extend(["couch","desk","coffee table"])
print(furniture)

Output

['bed', 'chair', 'bookcase', 'couch', 'desk', 'coffee table']

Deleting Elements with pop()

In addition to remove(), we can use the pop() method to remove elements from a list. Use the pop() method to remove an element at a specific index.

nums = [1,2,3,4]
nums.pop(1)
print(nums)

Output

[1, 3, 4]

The element located at index 1 was removed. If we don’t pass an index to pop(), it will remove the last item from the list.

# generate a list of numbers 1-10
nums = [x for x in range(1,11)]
# pop the last element off the list
nums.pop()
print(nums)

Output

[1, 2, 3, 4, 5, 6, 7, 8, 9]

Keywords

There are a couple of Python keywords that are handy when working with lists. The in keyword can be used to check whether or not an item is in a list. 

The syntax for using in looks like this:

list_item in list

Here’s an example of using the in keyword to find out if a list contains a specific string:

the_beatles = ["John","Paul","George","Ringo"]
print("Was John in the Beatles? ","John" in the_beatles)

Output

Was John in the Beatles?  True

Another useful keyword is not. By using not, we can determine if an element is absent from a string.

print("So Yoko wasn't a member of the Beatles? ","Yoko" not in the_beatles)

Output

So Yoko wasn't a member of the Beatles?  True

Reversing a List

The simplest way to reverse a list in Python is with the reverse() method. This method reorders the list so that the last element becomes the first element, and vice versa. 

Alternatively, we can traverse a list in reverse using Python slice notation.

superheroes = ["Batman", "The Black Panther", "Iron Man"]

# use slice notation to traverse the list in reverse
for hero_name in superheroes[::-1]:
    print(hero_name)

# use the reverse method to reverse a list in place
superheroes.reverse()

print(superheroes)

Output

Iron Man
The Black Panther
Batman
['Iron Man', 'The Black Panther', 'Batman']

List Sorting

Use Python’s sort() method to reorder the elements in the list. By default, sort() will rearrange the list so that the items it contains are in ascending order. For example, using sort on a list of numbers will order the numbers from least to greatest.

nums = [100,2003,1997,3,-9,1]

nums.sort()
print(nums)

Output

[-9, 1, 3, 100, 1997, 2003]

Alternatively, using sort() on a string will put the items into alphabetical order.

alphabet = ['B','C','A']

alphabet.sort()
print(alphabet)

Output

['A', 'B', 'C']

If you need to keep the original list intact, choose the sorted() method. The sorted() method returns a new list, leaving the original untouched.

nums = [7,2,42,99,77]
# sorted will return a new list
print("Modified list:", sorted(nums))
print("Original list: ", nums)

Output

Modified list: [2, 7, 42, 77, 99]
Original list:  [7, 2, 42, 99, 77]

List Indexing

The items in a list are referenced using an index. The index represents the order the item appears in the list.

The first item in a list is at index 0. The second is at index 1, and so on.

villains = ["Shredder","Darth Vader","The Joker"]

print(villains[0])
print(villains[1])
print(villains[2])

Output

Shredder
Darth Vader
The Joker

Unlike Python strings, lists can be altered. For instance, we can use Python to swap the contents of the first and third items in a list.

# swamp the first and third items of the list
temp = villains[2]
villains[2] = villains[0]
villains[0] = temp

There is, however, an easier way to swamp the list items in Python.

# swap list items with the power of Python!
villains[0],villains[2]=villains[2],villains[0]

Slicing

Python slicing allows us to retrieve multiple items from a list. The notation for slicing is a colon between the start and end of the desired range.

Syntax:

my_list[start:end:step] 

For a given list, slice notation looks for a starting index as well as an ending index. This tells Python the range of items we’re after.

Optionally, we can specify the step to traverse the list by. The step tells Python how to iterate through the list. We can provide a negative number, for instance, to traverse the list in reverse.

rainbow = ['red','orange','yellow','green','blue','indigo','violet']
print(rainbow[1]) # get the second item in the list
print(rainbow[:1]) # get items at indexes 0 and 1
print(rainbow[1:3]) # items at index 1 and 2
print(rainbow[:-1]) # all items excluding the last

Output

orange
['red']
['orange', 'yellow']
['red', 'orange', 'yellow', 'green', 'blue', 'indigo']

Loops and Lists

Because lists in Python are indexed, we can use loops to iterate through their elements.

# a list of random numbers in ascending order
nums = [2,4,7,8,9,10,11,12,13,15,16,17]
# a list of prime numbers
primes = [2,3,5,7,11,13,17]

# loop through a Python list
for num in nums:
    if num in primes:
        print(num,end="")

Output

2 7 11 13 17

List Methods

We’ve already seen examples of Python list methods such as reverse() and sort(). Unfortunately there is not enough room in this article to cover them all, but we’ve provided a list of the ones you should know about along with a description of what they do.

  • Append(): Add a new item at the end of the list.
  • Count(): Returns the total number of items in a list.
  • Clear(): Remove all the items from a list. 
  • Extend(): Join the elements of one list to the end of another.
  • Index(): Find the index of an item in the list. 
  • Insert(): Add an item to the list at a given index.
  • Pop(): Remove the last item from a list.
  • Remove(): Delete a specific item from the list.
  • Reverse(): Reorders the list from the last item to the first.
  • Sort(): Sort the list in ascending order.

Examples

Let’s end this article with some examples of using lists and list methods in Python.

Example 1: Find the sum of all the items in a list of numbers

nums = [98,62,77,84,89]

total = 0
for i in range(len(nums)):
    total += nums[i]

print("Total: ", total)

Output

Total:  410

Example 2: Find the average for a list of numbers

# find the average for a list of numbers
nums = [20,22,1.5,2,7,5.2,99]

total = 0
i = 0
while i < len(nums):
    total = total + nums[i]
    i = i + 1

average = total/len(nums)
print("The average to 2 decimal places: {:.2f}".format(average))

Output

The average to 2 decimal places: 22.39

Related Posts

The post Python Lists Cheat Sheet appeared first on PythonForBeginners.com.


Viewing all articles
Browse latest Browse all 22851

Trending Articles