what are lists in python programming
Answers
Trying to access an element other that this will raise an IndexError. The index must be an integer. We can't use float or other types, this will result into TypeError.
Nested list are accessed using nested indexing.
A list in python is a list of multiple characters. Many people get confused between a tupple and a list. Characters in a list are unchangeable while characters in changeable. The term we use here is mutable and immutable.
A list is represented by [ ]. A list can take in anything. Strings, integers, floats or even Boolean operators.
Let's take an example of a list. Say,
list_example = [1,2,3,4]
The number '1' is at an index 0. Index is the position of a character and for a list, the index starts with 0 and goes on.
Now, let's take about a few properties of a list.
If we say, print(list_example[0]), it prints 1.
If we say, print(list_example[1]), it prints 2
What we keep inside the [] is the index we want python to refer to.
Adding a character:
list_example.append(5)
Then, the list_example would change to [1,2,3,4,5]
Append feature always adds the character at the end of the list.
Adding a character at a specific place:
list_example.insert(x,y)
This takes in 2 variables.
x is the index you want y to place in.
If we say, list_example.insert(1,4)
Then, the list_example would be [1,4,2,3,4,5]
pop command:
list_example.pop()
Then, the outcome would be:
[1,4,2,3,4]
The pop() command removes/deletes the last character in the list.
Remove a character:
Let's say, we want to remove 2 in the list.
We simply type list_example.remove(2)
The outcome of the list would be [1,4,3,4]
If we want to remove a specific index, we first assign it a name and then remove it.
let's say we want to remove the character in the index position 1, which is 4.
Let's say:
number = list_example[1]
list_example.remove(number)
The list would the be:
[1,3,4]
Normal commands:
list_example.sort() - Sorts the characters in a ascending order or if it words/string, it goes in alphabetical order.
But, if we want it to be sorted in a reversed order, we turn the reverse as True.
list_example.sort(reverse = True )
__________
sum(list_example) - returns the addition of all characters.
_______
list_example.reverse() - reverses the order
_________
list_example.clear() - clears all the characters. The list becomes empty.
This is just a glimpse on list for python. Hope it helps! :)