Monday, December 2, 2019

Lists in Python

Index page for Python
http://mylearningcafe.blogspot.com/2015/08/python-index-page.html

What is a list?
Simply put, an ordered collection.

>>> list_of_integers = [1,4,5]
>>> len(list_of_integers)
3
>>> sum(list_of_integers)
10


How to get to an element in the list:

>>> list_of_integers[1]
4

Lists index starts from 0.

>>> list_of_integers[0]
1

Slice lists:

Slice lists using square brackets

>>> first_two_elements = list_of_integers[:2]
>>> first_two_elements
[1, 4]

Lets try some more commands:

>>> lists_of_value = [100,1,50,25,34,67,78,99]
>>> len(lists_of_value)
8

>>> first_4_elements = lists_of_value[:4]
>>> first_4_elements
[100, 1, 50, 25]

>>> last_3_elements = lists_of_value[-3:]
>>> last_3_elements
[67, 78, 99]

>>> copy_of_list_elements = lists_of_value[:]
>>> copy_of_list_elements
[100, 1, 50, 25, 34, 67, 78, 99]

>>> copy_of_list_elements.extend([200,300,400])
>>> copy_of_list_elements
[100, 1, 50, 25, 34, 67, 78, 99, 200, 300, 400]


Index Page for Python:
http://mylearningcafe.blogspot.com/2015/08/python-index-page.html



No comments:

Post a Comment