November 24, 2019

Python tutorial 12 | Lists

Let us move to the next tutorial in the Python Tutorials for Beginners. This Python beginner tutorial explains lists in Python. The tutorial also shows a variety of operations that we can do on Python lists.

What are lists? In Python programming, a list is a group of values. These values are called items. The items are commonly of the same data type like all integers or all floats. But, it is possible for the items to be of different list data types like strings, integers or floats. Lists are mutable, meaning that we can change a list. A list may have another list as an item. The lists which are items of another list are called nested lists. The list syntax is:

[item0, item1, item2,..., itemn]

In the above list format, note that the list is put between square brackets [ and ]. Within the list, the items are separated by commas. The item indexes start from 0. Now, let us see Python list examples and list operations with Python examples.

# Python code
points = [1, 2, 10, 100]
# print the Python list i.e. 1, 2, 10 and 100
print (points)

# Indexing list operation means getting a single item from a Python list
# print the first item (of index 0) of the Python list i.e. print 1
print (points[0])
# print the third item (of index 2) of the Python list i.e. print 10
print (points[2])

# Slicing list operation means getting a section of a Python list
# print the list from index 1 up to but excluding index 3 i.e. print 2 and 10
print (points[1:3])
# print the list from index 1 up to the end of the list i.e. print 2, 10 and 100
print (points[1:])

# change an item in the list
points[0] = 3
# print the updated list i.e. 3, 2, 10 and 100
print (points)
# remove items from the list, from index 3 up to the end of the list
points[3:] = []
# print the updated list i.e. 3, 2 and 10
print (points)
# concatenation, meaning adding two or more lists together
points = points + [200, 300]
# print the updated list (with 5 items now), 3, 2, 10, 200 and 300
print (points)

# in operator (to check list membership)
# print False, because the item, 1 is not in the list
print (1 in points)
# print True, because the item, 2 is a member of the list
print (2 in points)
# not in operator (to check if an item is not a member of the list)
# print True, because the item, 4 is not a member of the list
print (4 not in points)

# Python code
# list function (to convert a range or a string to a list)
# convert range to list
new_points = list (range(6))
# print the items of the list, which are 0, 1, 2, 3, 4 and 5 (range excludes 6)
print (new_points)
# convert string to list
letters = list ('STS')
# print the items of the list, which are 'S', 'T' and 'S'
print (letters)

Want to see Python samples like the above working with a list of string items? View my Python video tutorial 12. Thank you.

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.