Python: 7 Lists
A list is a collection that is ordered and has changeable content.
There are other data collection methods in python such as:
- List is a collection which is ordered and changeable. Allows duplicate members.
- Tuple is a collection which is ordered and unchangeable. Allows duplicate members.
- Set is a collection which is unordered and unindexed. No duplicate members.
- Dictionary is a collection which is unordered, changeable and indexed. No duplicate members.
Find out more about them on the W3 schools site
You might hear about arrays in other programming languages. Python doesn't support Arrays, lists are the closest that Python has to them.
Lists are pieces of data that can be identified with [ ]
fruit = ["apple", "banana", "chicken", 293, "durian"]
This list above has five items.
Lists in Python can have multiple types of data stored inside them. It's good practice to keep the data in a list to one data type where possible.
Each item has a position.
In programming we start counting at 0, so the first position is position 0. These positions are known as indexes.
fruit[0] would get the first item in the list "apple"
Note that typing just the variable name of the list will print out the entire contents of the list. This is useful for checking the contents of a list when testing or initially writing a program.
fruit[0] will get just the data at that index of the list.
We can also find the length of a list by using the len() function
Inside the brackets () we put the content to find the length of
As shown in the code example above the number 5 is printed.
We can also remove items from the list
We use the del keyword to do this.
For more information check out the W3 Schools page on Python Lists
You can find more information on strings and manipulating them in Python here on W3 Schools