Python 3 - Data types - Using a list

The list data type is like a container.

So we can manage it like an array in other programming languages.

In this tutorial of the Python 3 data type list, we are going to play with all methods of the list.

You can find the count() and index() methods in the listManager() function that I created below.

Code

''' Display what there is into myList '''
def listManager(myType, myList):
    i = 0
    name = 50
    listSize = myList.__len__()
    
    print("\n--> " + myType)
    
    print("Number of items = " + str(listSize))
    print("Number of \"" + str(name) + "\" value = " + str(theList.count(name)) + ".")
    
    try:
        occurrence = theList.index(name)
    except ValueError as myError:
        print("Error:", myError)

    print("The first occurrence of " + str(name) + " is at index: " + str(occurrence) + ".")
    
    for i in myList:
        print(i)
''' End of listManager '''

theList = ["Hello", "World", 50]
listManager("classic", theList)

theList.append("Hello")
listManager("append", theList)

theList[0] = 21
listManager("adding by index", theList)

theList.insert(1, "John")
listManager("insert", theList)

secondList = [34, 12, 57, "Gorgeous"]

theList.extend(secondList)
listManager("extend", theList)

theList.pop()
listManager("pop", theList)

theList.remove("World")
theList.remove("John")
theList.remove("Hello")
listManager("remove", theList)

theList.sort(key=None, reverse=False)
listManager("sort", theList)

theList.reverse()
listManager("reverse", theList)

Result

--> classic
Number of items = 3
Number of "50" value = 1.
The first occurrence of 50 is at index: 2.
Hello
World
50

--> append
Number of items = 4
Number of "50" value = 1.
The first occurrence of 50 is at index: 2.
Hello
World
50
Hello

--> adding by index
Number of items = 4
Number of "50" value = 1.
The first occurrence of 50 is at index: 2.
21
World
50
Hello

--> insert
Number of items = 5
Number of "50" value = 1.
The first occurrence of 50 is at index: 3.
21
John
World
50
Hello

--> extend
Number of items = 9
Number of "50" value = 1.
The first occurrence of 50 is at index: 3.
21
John
World
50
Hello
34
12
57
Gorgeous

--> pop
Number of items = 8
Number of "50" value = 1.
The first occurrence of 50 is at index: 3.
21
John
World
50
Hello
34
12
57

--> remove
Number of items = 5
Number of "50" value = 1.
The first occurrence of 50 is at index: 1.
21
50
34
12
57

--> sort
Number of items = 5
Number of "50" value = 1.
The first occurrence of 50 is at index: 3.
12
21
34
50
57

--> reverse
Number of items = 5
Number of "50" value = 1.
The first occurrence of 50 is at index: 1.
57
50
34
21
12

A great data type, isn't it? laugh

Add new comment

Plain text

  • No HTML tags allowed.
  • Lines and paragraphs break automatically.