Hey there Steemers, today we will be learning how to use and create Lists in Python Programming. The most common List types used are Lists and Tuples. I will be going over one of them in today's Python Lesson.
What are Python Lists?
Python Lists are the most versatile datatype in Python. They can be written as a list of comma separated values which are housed in square brackets. Lists in Python do not need to use a consistent data type i.e. Integer, String, Float.
How do I create a List?
Lists are super simple to create. You simply put different values separated with commas and house them with square brackets! The format looks like the following:
list1 = ['maths', 'science', 'english', 2002, 1234]
list2 = [1, 2, 3, 4, 5]
list3 = ['a', 'b', 'c', 'd', 'e']
How do I select a certain value from a List?
If you want to select a certain value from your List, you can slice them. This allows you to single out value, which is good of you have a lot of values. When we start a list, the indices start at 0. We can slice lists by setting our code in the following format:
list1 = ['maths', 'science', 'english', 2002, 1234]
list2 = [1, 2, 3, 4, 5]
print(list1[1:5])
print(list2[0:3])
The results should look like this:
Updating Lists
Your List values can be updates by giving the slice on the left side an assignment operator. You can add the values in a List using the append() method. You would set out your code like this:
list = ['maths', 'science', 'english', 2002, 1234]
print("Value available at index 3 : ")
print(list[3])
list[3] = 2004
print("New value available at index 3 : ")
print(list[3])
As you can see, the code will change 2002 to 2004. The output of the code can be found below:
Deleting values from a List
We can delete values from a list by using the del statement. This statement is only handy if you know what value you want to remove. You can use the remove() method if you are unsure. Example code can be found below:
list = ['maths', 'science', 'english', 2002, 1234]
print(list)
del list[2];
print("After deleting value at index 2 : ")
print(list)
The code above removes 'english' from the List, but it will still remain in the original List.
Thank you for tuning in on today's Python Programming Lesson about Lists. I hope you enjoyed it! Follow me so you know when I release my Coding Lessons :)
See you later,
Jack.