Earn 20 XP


List in Python

  • As the name suggests, List is an ordered sequence of data. In real life, if you could make a list of things that come to your mind (or event for any specific purpose), it could be something like this –

    • Brush
    • Leuven
    • 48851964400
    • 3.14
    • Mom
  • Well, this is my list. You could make your list & include whatever you want in it. So, in my list, I have included what I do early in the morning, my city, my mobile number, the value of pi to two digits, and mom. It has different types of data – strings, float, and integer.

  • This is the kind of flexibility Python List provides. It can hold different types of data types. Declaring a List is pretty straightforward. You use square brackets ([]) and separate the items by a comma. Let me write an example -
    A = ["Brush", "Leuven", 48851964400, 3.14, "Mom"]

  • Lists are mutable. Say if you want to change some item on a List, you can do that. For example, if I don’t like ‘Brush’ and want to replace this with ‘Morning Walk’, I can do it –
    A = ["Morning Walk", "Leuven", 48851964400, 3.14, "Mom"]

  • Some essential features of Python lists are:

    • Collection of values
    • Can be of any data type
    • Can be a combination of different types

Note: The tutor in this video used a Python console. Nothing to worry about here; you can use the same code and run it on a Jupyter notebook too.

List Methods

.append()

In Python, you can add values to the end of a list using the .append() method.

image.png

count()

The .count() Python list method searches a list for whatever search term it receives as an argument, then returns the number of matching entries.

image.png

len()

The Python len() function can determine the number of items found in the list it accepts as an argument.

image.png

.sort()

The .sort() Python list method will sort the contents of whatever list it is called on. Numerical lists will be sorted in ascending order, and lists of Strings will be sorted in alphabetical order. It modifies the original list and has no return value.

image.png

Tuples in Python

  • Tuple is also an ordered sequence of items as a List. Tuple also holds multiple data types.
  • The only difference between Tuple & List is that Tuple is immutable; once created, it cannot be changed.
  • Creating a tuple is as simple as putting different comma-separated values within round brackets.
  • Example: A = (‘Brush’, ‘Leuven’, 48851964400, 3.14, ‘Mom’)

Note: The tutor in this video used a Python console. Nothing to worry about here; you can use the same code and run it on a Jupyter notebook too.