Sunday, April 20, 2025

Python Length, Indexes

From last tutorial we know how to get total number of elemens in list:


names =["Michael", "Samantha", "Anastasia"]

lol = len(names)
print("Number of elements: ", lol)

Result: 


Number of elements:  3
>>> 

Also, as with strings, to get specific character we can use positions/indexes enclosed in brackets. First element is at position 0:


names =["Michael", "Samantha", "Anastasia"]

print("Element 0 :", names[0])
print("Element 1 :", names[1])
print("Element 2 :", names[2])

Result: 


Element 0 : Michael
Element 1 : Samantha
Element 2 : Anastasia
>>> 

Often, it's useful to grab elements of one list and store it in another one, changing order of them:


names =["Michael", "Samantha", "Anastasia"]

mix = (names[2], names[0], names[1])

print(mix)

print("Element 0 :", mix[0])
print("Element 1 :", mix[1])
print("Element 2 :", mix[2])

Result: 


('Anastasia', 'Michael', 'Samantha')
Element 0 : Anastasia
Element 1 : Michael
Element 2 : Samantha
>>> 

In next tutorial, we will learn how to Change, Append and Insert elements in existing lists.

No comments:

Post a Comment

Tkinter Introduction - Top Widget, Method, Button

First, let's make shure that our tkinter module is working ok with simple  for loop that will spawn 5 instances of blank Tk window .  ...