About the author
You should now be able to do some programs that are much more interesting. If you have been keeping up, you should realize that now you can combine all the other things you have learned with if-statements and boolean expressions to make your programs do smart things.
A list is exactly what its name says—a container of things that are organized in order. It’s not complicated; you just have to learn a new syntax. First, there’s how you make a list:
hairs = ['brown', 'blond', 'black']
eyes = ['black', 'brown', 'blue']
weights = [60, 70, 80, 90]
What you do is start the list with the [ (left bracket), which “opens” the list. Then you put each item you want in the list separated by commas, just like when you did function arguments. Lastly, you end the list with a ] (right bracket) to indicate that it’s over. Python then takes this list and all its contents and assigns them to the variable.
Now we will create some exercise with List and see how it works.
Let's see output first to understand this.
Let's understand the output step by step
First, we defined 3 Lists.
On line 5, we printed List. When you print List python simply print the entire list starting with [ and ending with ] keeping all element separated with ','.
On line 6, we printed the length of List. It will print how many elements a List has. If you use len() function on a string it will print length of that string.
On line 7, just like the string index of the List also start from 0. So in our List at place 1 we will have 'blond'. You can also use [0:2] to print multiple elements.
To add new elements in a List you can use append() function.
The append() will add an element at the end of List.
You can convert a text into list using split function.
line1 = "This is some line"
list1 = line1.split()
print(list1) # This will result ['This','is','some','line']
by default split use " " (space) to split and create a list, you can use other keywords also e.g line1.split(','), This will split based on ','.
Try all functions of List.
Try passing a string in extend function.
Try more of split function (this is a very useful function while handling data.)
About the author
Please login to comment