Sunday, April 20, 2025

Python Change, Insert, Append

We can change element using positions:


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

names[0] = "Patrick"
print(names)

Result: 


['Patrick', 'Samantha', 'Anastasia', 'John']
>>> 

New elements can be inserted using insert() function. Even duplicates:


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

names[0] = "Patrick"
names.insert(1, "Madona")
names.insert(2, "Madona")

print(names)

Result: 


['Patrick', 'Madona', 'Madona', 'Samantha', 'Anastasia', 'John']
>>> 

Sure, we can append new elements at the end of list using append() function:


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

names[0] = "Patrick"
names.append("Brian")
names.append("Larry")

print(names)

Result: 


['Patrick', 'Samantha', 'Anastasia', 'John', 'Brian', 'Larry']
>>> 

We can also transfer elements of one list into another one - using for loop:


names =["Michael", "Samantha", "Anastasia", "John"]
names1 = ["Patrick", "Madona", "Larry"]

for x in names1:
    names.append(x)

print(names)

Result: 


['Michael', 'Samantha', 'Anastasia', 'John', 'Patrick', 'Madona', 'Larry']
>>> 

In next tutorial, we will learn how to Delete, Remove and Pop elements from 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 .  ...