Python List

Posted by syed on Sat, 19 Feb 2022 16:28:49 +0100

Link to the video course "the art and Tao of Python Programming: an introduction to Python language": https://edu.csdn.net/course/detail/27845

Data types in Python

Composite data type - Collections

There are four Collection data types in the Python programming language:

  • A list is an ordered and changeable Collection. Duplicate members are allowed.
  • Tuples are ordered and unchangeable collections. Duplicate members are allowed.
  • A Collection is an unordered and indexed Collection. There are no duplicate members.
  • A dictionary is an unordered, changeable, indexed Collection. There are no duplicate members.

List

List introduction

List is the most frequently used data type in Python.

A list is an ordered collection of elements (items) stored in a variable. These items should be related in a certain relationship, but there is no limit to what can be stored in the list. (the list is a basket, which can hold everything!)

A list is a sequence of values (similar to an array in other programming languages but more versatile)

The values in a list are called items or sometimes elements.

The important properties of Python lists are as follows:

  • Lists are ordered – Lists remember the order of items inserted.

  • Accessed by index – Items in a list can be accessed using an index.

  • Lists can contain any sort of object – It can be numbers, strings, tuples and even other lists.

  • Lists are changeable (mutable) – You can change a list in-place, add new items, and delete or update existing items.

students = ['ben', 'allen', 'calvin']

for student in students:
    print("Hello, " + student.title() + "!")
Hello, Ben!
Hello, Allen!
Hello, Calvin!
# A list of mixed datatypes
L = [ 1, 'abc', 1.23, (3+4j), True]
print(L)
[1, 'abc', 1.23, (3+4j), True]
# An empty list
L = []
print(L)
[]

Name and define a list

Since lists are collections of elements (items, data items), it is best to specify plural names for them. If each item in the list is a dog, you can name the list "dogs".

In Python, a list is described by enclosing its internal elements in square brackets and separating them with commas.

dogs = ['border collie', 
        'poodle', 
        'german shepherd']

You can use Python's list() constructor to convert other data types to lists.

Example: convert a string to a list of single character strings

L = list('abc')
print(L)    # ['a', 'b', 'c']
['a', 'b', 'c']

Example: converting tuples to lists

L = list((1, 2, 3))
print(L)    # [1, 2, 3]
[1, 2, 3]

Access elements in the list

Items in the list are identified by their position in the list, and the index starts from zero.

To access the first element in the list, specify the name of the list, followed by a zero in parentheses. The number in parentheses is called the index of the item.

Since the list starts from zero, the index of the item is always 1 less than the position in the list. Therefore, to get the second item in the list, you need to use index 1, and so on.
Therefore, Python is considered a zero indexed language (like many other languages, such as C or Java)

# Example: Access 1st and 3rd list items
L = ['red', 'green', 'blue', 'yellow', 'black']
print(L[0])  # red
print(L[2])  # blue
red
blue
dogs = ['border collie', 
        'poodle', 
        'german shepherd']

dog = dogs[0]
print(dog.title())
dog = dogs[1]
print(dog.title())
Border Collie
Poodle

If the index used exceeds the number of item s in the list, an IndexError error error will be raised.

# IndexError: list index out of range
L = ['red', 'green', 'blue', 'yellow', 'black']
print(L[5])
---------------------------------------------------------------------------

IndexError                                Traceback (most recent call last)

<ipython-input-8-e5c74a10193c> in <module>
      1 # IndexError: list index out of range
      2 L = ['red', 'green', 'blue', 'yellow', 'black']
----> 3 print(L[5])


IndexError: list index out of range

Access the last element of the list

To get the last item in the above list, use index 2, but this works only for lists with exactly three elements. To get the last item in the list, you can use index - 1 regardless of the length of the list.

L = ['red', 'green', 'blue', 'yellow', 'black']
print(L[-1])    # black
print(L[-2])    # yellow
black
yellow
dog = dogs[-1]
print(dog.title())
German Shepherd

This syntax also applies to the penultimate item, the penultimate item, and so on.

dog = dogs[-2]
print(dog.title())
Poodle

However, negative numbers greater than the length of the list cannot be used.

dog = dogs[-4]
print(dog.title())
---------------------------------------------------------------------------

IndexError                                Traceback (most recent call last)

<ipython-input-12-18cbc6479bf9> in <module>
----> 1 dog = dogs[-4]
      2 print(dog.title())


IndexError: list index out of range

Lists and loops

Access all elements of the list

This is one of the most important concepts related to lists.
We use loops to access all the elements in the list.

A loop is a block of code that is reused until it finishes processing the element to be processed, or until a condition is met. In this example, a loop is run for each item in the list. For a list of three items, the loop will run three times.

Let's see how to access all the elements in the list.

dogs = ['border collie', 'poodle', 'german shepherd']

for dog in dogs:
    print(dog)
border collie
poodle
german shepherd

Inside and outside the cycle

Python uses indentation to determine what's inside and outside the loop. The code in the loop will run on each element in the list. Code without indentation after the loop will run once as normal code.

dogs = ['border collie', 'poodle', 'german shepherd']

for dog in dogs:
    print('I like ' + dog + 's.')
    print('No, I really really like ' + dog +'s!\n')
    
print("\nThat's just how I feel about dogs.")
I like border collies.
No, I really really like border collies!

I like poodles.
No, I really really like poodles!

I like german shepherds.
No, I really really like german shepherds!


That's just how I feel about dogs.

Note that after the loop completes, the last line runs only once.

Traversal list

When looping through the list, you may want to know the index of the current item. You can use list Index (value) syntax, but there is a simpler way. The enumerate() function can be used to track the index of each element because it loops through the list:

dogs = ['border collie', 'poodle', 'german shepherd']

print("Results for the dog show are as follows:\n")
for index, dog in enumerate(dogs):
    place = str(index)
    print("Place: " + place + " Dog: " + dog.title())
Results for the dog show are as follows:

Place: 0 Dog: Border Collie
Place: 1 Dog: Poodle
Place: 2 Dog: German Shepherd

enumerate provides a concise syntax to obtain both subscripts and current values while iterating through an iterator in a loop.

To traverse the list, you need to add an index variable to save the current index. Not use

    for dog in dogs:

But with

    for index, dog in enumerate(dogs)

The value in the variable index is always an integer. If you want to print as a string, you must convert an integer to a string:

    str(index)

The index always starts from 0, so in this example, the value of place should actually be the current index plus 1:

dogs = ['border collie', 'poodle', 'german shepherd']

print("Results for the dog show are as follows:\n")
for index, dog in enumerate(dogs):
    place = str(index + 1)
    print("Place: " + place + " Dog: " + dog.title())
Results for the dog show are as follows:

Place: 1 Dog: Border Collie
Place: 2 Dog: Poodle
Place: 3 Dog: German Shepherd

Topics: Python list