Python Programming

List in Python

In Programming, Python by Baqir Ali

The list is a variable that stores multiple items in a single variable. The list in python somehow similar to the array in other languages but we can not call them array as the array stores the homogeneous data type and the list can store values of any data type. The following is the example of a list that stores the names of students inside the variable ‘students’.

students=["Ali","Khan","John","Sam"]

Each item in the list has an index value which shows the position of value inside the list and the index value starts from 0 to end-1.

Example 1: Printing a specific value from list

students=["Ali","Khan","John","Sam"]
print(students[0])

Output: Ali

Example 2: Using range to print items from the list.

students=["Ali","Khan","John","Sam"]
print(students[0:2])

Output: [‘Ali’, ‘Khan’]

Example 3: Loop through the list

students=["Ali","Khan","John","Sam"]
for names in students:
    print(names)

Output:

Ali
Khan
John
Sam

Example 4: Storing multiple data type values

values=["Khan",2.5,300]
print(values[0],' ',values[1],' ',values[2])

Output: Khan 2.5 300

Example 5: Create a list of appointments made and ask the new guests reaching at restaurant their name. If the name is on the list greet them else sorry.

database=["Ali","Khan","John","Sam"]
guest=input("What is your Name sir? ")
result=False
for name in database:
    if name==guest:
        result=True

if result:
    print("Wellcome Sir")
else:
    print("Sorry Sir")

Output:

What is your Name sir? James
Sorry Sir

What is your Name sir? Khan
Wellcome Sir

Exampel 6: Finding maximum number from the list

numbers=[25,45,12,115,47,58,65,42,54]
max=numbers[0]
for item in numbers:
    if item>max:
        max=item

print("The maximum number is ",max)

Output:

The maximum number is 115

Support us by sharing this post