Python Lists

published on: | by cindy In category: Python

Lists are the most versatile python data structure and stores an ordered sequence of elements just like your shopping list or to-do-list. In Python, Lists are mutable, meaning that the elements can be altered unlike tuples and strings.The elements of a list are called items and can be any data type.

Creating Lists in Python

Creating lists in python is quite simple, to define the list use square brackets [ ] and separate the items in the list with a comma.

mylist = [ ]  # empty list
mylist2 = [1, 2]  # list containing 2 items with integers
# list with 3 items, mixed data types, integers, and a string
mylist3 = [1, 2, 'hello']

Note

  1. A list can be empty or contain any number of items with different data types(integers, float, strings, etc.).
  2. It is a good practice to use plural names when defining lists, just to make your code readable.
  3. A list can also hold another list as an item, these are called nested lists. .See this illustration Programming = [python', ' php ', [1, 2, 3] ] # a nested list

Accessing items in a list

We can access items in a list by using the name of that list followed by the index(position) of the item. Each item in a list has an assigned index value. The first index of an item is 0 and must be an integer.Use the index operator [ ].To illustrate this, let's create a list holding students names

# Define a list of Students
students = ['Cindy', 'Tess', 'Monica', 'Daniel']

# To get the first listed student Cindy
first_student = students[0]
print(first_student)

# To get the second student Tess
second_student = students[1]
print(second_student)

# To get the last student Daniel
last_student = students[-1]
print(last_student)

Negative Index

Python also supports negative indexing. The negative indexing is useful when you want to get the last item in a list because it starts accessing a list from the end.

Note

  1. The first item of any non-empty list is [0].
  2. The last item of any non-empty list is [-1].

Slicing of a List

Slices are good for getting a subset of items in a list. It uses the slicing operator : (colon) to extract part of the sequence. Let's define a list of programming languages to illustrate how to create subsets from it.

# define a list
languages = ['java', 'python', 'perl', 'ruby', 'C#']
# slicing everything up to but not including index 3
first_three = languages[:3]
print(first_three)  # ['java', 'python', 'perl']

# slicing everything from index 3 to the last item
third_last = languages[3:]
print(third_last)  # ['ruby', 'c#']

# elements from beginning to end
list_all = languages[:]
print(list_all)  # ['java', 'python',''perl','ruby', 'c#']

# elements from 1st to 3rd item
languages[0:3]
print(languages[0:3])  # ['java', 'python', 'perl']

# last three elements
list_three = languages[-3:]
print(list_three)  # ['perl','ruby', 'c#']

Finding the length of a list

Python has useful in-built functions that work with the list. We will discuss them later but for now, len() function help us in returning the total number of elements in a list.

# define a list
languages= ['java', 'python', 'perl', 'ruby', 'c#']
# print the length of the list
print(len(languages))
# output 5

Modify elements in a list

At this point, you have learnt how to access individual items in a list. Remember lists are mutable therefore, its possible to change the values, insert elements to it , remove some elements and even sort the elements in list

Change the Value of an Existing Item

Consider the languages list we created in the example above. Change the value of the first index to kotlin and the last index to anything you want, c++ for me.

# define a list of programming Languages
languages = ['java', 'python', 'perl', 'ruby', 'c#']
# access the first index and Change the value to kotlin
languages[0] = 'Kotlin'
# print the first item to see if it has been modified
print(languages[0])

# access the last index and Change the value to kotlin
languages[-1] = 'c++'
# print the last item to see if it has been modified
print(languages[-1])

# print the new list,
# pay attention to the first and last index
print(languages)  # ['Kotlin', 'python', 'perl', 'ruby', 'c++']

How to add items to a list

There are two ways of adding elements to a list. You can either append an item at the end of the list or by inserting at a specific location position.

list.append(item)

The default behavior of list.append(item) is to add items at the end of the list .

# define a list of programming languages
languages = ['java', 'python', 'perl', 'ruby', 'c#']
# append c
languages.append('c')
print(languages)
# Output : ['java', 'python' ,'perl', 'ruby', 'c#', 'c']
# try something cool to find the last item,
# use **negative index** to find the value of the last item
print(languages[-1])
# should give you c

list.insert(i, item)

This method will insert an item at the ith position in a list, shifting elements to the right.

# use the languages list we defined in the above example.
# This time insert 'c' at the first index

# define a list
languages = ['java', 'python', 'perl', 'ruby', 'c#']

# insert c in the first position
languages.insert(0, 'c')
print(languages)  # ['c', 'java', 'python', 'perl', 'ruby', 'c#']

# insert kotlin in the third position
languages.insert(2, 'Kotlin')
print(languages)  # ['c', 'java', 'Kotlin', 'python', 'perl', 'ruby', 'c#']

Removing elements in a list

You can remove elements of a list by value or its position. Use the del keywords to delete an item at a specific index(by position)

  • single item
# define a list
languages= ['Java', 'Python', 'Perl', 'Ruby', 'C#'] 
del languages[2]  # use del keyword to remove Perl
print(languages)#removes perl ['java','python', 'ruby', 'c#']
  • Multiple items
# define a list
languages= ['Java', 'Python', 'Perl', 'Ruby', 'C#'] 
del languages[1:3]  # delete Multiple items by slicing
print(languages)#removes  ['java', 'ruby', 'C#']

Use list.remove(item) method to remove by value.It will search and remove only the first occurrence of an item.

# define a list
Languages = ['java', 'python', 'perl', 'python', 'ruby', 'c#'] 
Languages.remove('python')  # remove only the **first occurrence** of python

Note

It removes the python after java. Note that the 'python' after Perl is still present

Popping elements in a list

Unlike del() and remove() which do not return a value, pop() returns the object.By default it removes and returns the last item of a list

 languages= ['java', 'python', 'perl', 'ruby', 'c#']
print(languages.pop())  # print c#

list.pop(i).

You can also specify the specific item to remove. list.pop(i). Removes and returns the ith item in a list

Languages= ['java', 'python', 'Perl', 'ruby', 'C#']
print(languages.pop(1))  # removes  index 1 item
#  Output returns Python

Common List Operations and Methods

list.clear()

Removes all items in a list

# define a list of programming languages
languages = ['java', 'python', 'perl', 'ruby', 'c#']
# clear
languages.clear()
print(languages) # []

list.count(item)

Returns the number of times an item appears in the list. It takes one argument

list.reverse()

Reverse the order of items in a list

list.sort()

The sort method as the name suggest sorts the items in a list in ascending, descending and also as defined by a user. by default, the method will sort the items in ascending order. To sort in descending order pass reverse=True as a parameter

# Define a list of Students
students = ['Cindy', 'Tess', 'Daniel', 'Rachel', 'Alberts']

# sort in ascending order
students.sort()
print(students)
# outputs ['Alberts', 'Cindy', 'Daniel', 'Rachel', 'Tess']

# sort in descending order
students.sort(reverse=True)
print(students)
# outputs ['Tess', 'Rachel', 'Daniel', 'Cindy', 'Alberts']

list.index(item)

When lists start to get long, it becomes more difficult to count the items and determine at what index position a certain value is located. uselist.index(item), to return the index in the list where that item is located. If there is more than one item with value item, this method will return the first occurrence.

Repetition

uses the * Operator. Concatenates a list a repeated number of times python

mylist= ['strings are  cool'] * 2
print(mylist)
# output:  ['strings are  cool', 'strings are  cool']

Membership

Keyword in is used to test if an item is a member of a list.

languages = ['java'', 'python' ,'perl', 'ruby', 'c  # ']
if 'python' in languages:
    print('right')

List concatenation

List concatenation is combining lists to create a new list object.You can either use + operator or extend() method to join lists

  1. list.extend(iterable)

The extend method concatenates lists by adding the items of the list passed as an argument to an existing list.It does not create a new list.Note that you do not call extend with multiple arguments; it takes in a second list as its argument.

# define a list
languages = ['java', 'python', 'perl', 'ruby', 'C#']
Languages2 = ['c++', 'C'] # define a second list
languages.extend(Languages2)
print(languages.extend(Languages2))
# Output ['Java', 'Python','Perl', 'Ruby', 'C#'']

Note

The extend() does not return any value, instead, it modifies the original list by adding the content of the second list

  1. Concatenation using the + operator
# define a list
languages= ['java', 'python', 'perl', 'ruby', 'c#', ]
print(languages + (['C++', 'C']))
# Output:  ['java', 'python' ,'perl', 'ruby', 'c#', 'C++', 'C']

Copying a list

use list.copy() or slicing to copy a list.Copying is mostly used to create a temporary version of an existing list so that you can modify it rather than the original list.copy()

Why copy a list using [:]

The best way to copy a list is by using [:]. If you copy a list without using this approach, whatever you do to the copied list will affect the original.

Iteration in Lists

Lists can contain many items and loopings an efficient way to access each item at a time and store it in a temporary variable. The variable name should be the singular version of the list name for consistency and readability. The indented block of code makes up the body of the loop, where you can work with each individual item. Any lines that are not indented run after the loop is completed.

For Loop

Used to iterate through each element on a list with the keyword in.The for loop allows you to to perform an action for every element in the list.

illustration 1

languages= ['java', 'python', 'perl', 'ruby', 'c#']
for i in languages:
    print(i)

This will print all the items in the list one per line as shown below:

java
python
perl
ruby
 c

illustration 2

random_sum = [2, 7, 8, 9]
total= 0
for i in random_sum:
    total += i
print(total)

The above code will print 26, the sum of all the items of the list. The for loop requires a variable to hold the items being iterated and the source.

While Loop

will first check the condition. If the condition is true, it will keep iterating and terminates the loop once the condition turns false.

languages = ['java', 'python', 'perl'' 'ruby', 'c  # ']
 i= 0
while i < len(languages):
     print(languages[i])
 i= i+3

The above codes will print java ruby

Generating Large Lists of numbers using range()

The range() works with a set of numbers efficiently. The range function starts at 0 by default and stops one number below the number passed.

To understand the range() better, let's generate and print a numbers from 0-10

numbers= []
for number in range(11):
    print(number)

we can se the range() with list() to make a list of numbers between 1 and 10

# Make a list of numbers from 1-10
numbers = list(range(1, 10))
#  output [1, 2, 3, 4, 5, 6, 7, 8, 9]

List comprehension

Provide a more elegant way of creating lists with way lesser code than using the for loops. To write a comprehension, define an expression, the values you want to store in the list. Then write a for loop to generate input values needed to make the list. list_variable= [x for x in iterable] we are going to create a for loop that print the letters of a string

# print the letters in the word 'python'
name_letters = [ ]
for name in  'Python':
    name_letters.append(name)
print(name_letters)

we could simply write the above using list comprehensions as

name_letters = [name for name in  'python']
print(name_letters)

Conclusion

Now you know what lists are and how to manipulate them. This is simply an introduction.Practice more to master the concepts .Leave a comment below for any queries and Follow me on twitter