Image

Anyone Can Code.





Image

Introduction to Lists

Sammarth Kumar



A list is an ordered sequence of data which is mutable (it's values can be overwritten) and can also contain multiple data types. For example, we can have lists with strings, ints, floats, etc.
To create a list, we use Square Brackets [].
An example of a list with identifier list1 is list1 = [3,4,"5",6.0]
We can also create lists as elements of lists. These are known as nested lists.
For example, list2 = [3,4,[5,6],7]nests the list [5,6] in list2

Accessing Lists

To access elements in a list, we use indexing, the same thing we did with strings, but here each index represents an element in a list whereas in a string each index represented a character in the string.

1
2
list1 = [3,4,5,6]
print(list1[2])

Output

5

1
2
list2 = [3,5,4,2,[4,5]]
print(list2[4][0]) #to get the first element in the nested list

Output

4

Mutability

Lists are mutable data types and their contents can be overwritten.

1
2
3
4
list3 = [3,4,5,6]
print(list3)
list3[3] = 4
print(list3)

Output

[3, 4, 5, 6]
[3, 4, 5, 4]

Here you can see we gave a new value to the fourth element in the list. This was only possible due to the mutable nature of lists.


That's it for this tutorial! Scroll up and click on Next for the next tutorial!

For information on how you can use this information, please refer to our Terms of Use


Copyright © 2020, Q-Programming | Created by Arjun Sodhi, Balpreet Juneja and Sammarth Kumar | Developed and Designed by Sammarth Kumar