Examples of List usage in Python.

As we know how to define lists in python from the post: http://ngelinux.com/lists-in-python/

However lists are used frequently in python and we should know how to play with them.

Lets see below program with various different ways to use lists.

List Examples

# 1. Define List 
friends = ["Kevin", "Karen", "Jim", "OSCAR","TIDE"]

# 2. Printing a set of elements
print("1st to 3rd element")
print(friends[1:4])
print("\n")
# Negative index starts from back.
# Hence you can refer negative index also to read from last.

# 3. Print complete list
friends[1]="Mahesh"
print("All lists:")
print(friends)

# 4. Combining two lists
facebook_friends=["Moh", "Lui", "Santa", "Charlie"]
print(facebook_friends)
friends.extend(facebook_friends)
print("\nAll friends with added element at index 1 are:  ")

# 5. Adding a new element at index 1
friends.insert(1,"NEWFRIEND")
print(friends)

# 6. Removing an element.
friends.remove("Kevin")
print("\nKevin friend removed:")
print(friends)

# 7. Check if an element exists in the list
print(friends.index("Santa"))
## print(friends.index("Kelly"))   ## Throws an error as it doesn't exists.

# 8. Pop an element to remove it.
# Use sort to sort the list
friends.sort()
print(friends)

# 9. Empty List
friends.clear()
print("\nAll friends cleared:")
print(friends)

 

Output

/Users/saket/PycharmProjects/1helloworld/venv/bin/python /Users/saket/PycharmProjects/1helloworld/lists.py
1st to 3rd element
['Karen', 'Jim', 'OSCAR']


All lists:
['Kevin', 'Mahesh', 'Jim', 'OSCAR', 'TIDE']
['Moh', 'Lui', 'Santa', 'Charlie']

All friends with added element at index 1 are:  
['Kevin', 'NEWFRIEND', 'Mahesh', 'Jim', 'OSCAR', 'TIDE', 'Moh', 'Lui', 'Santa', 'Charlie']

Kevin friend removed:
['NEWFRIEND', 'Mahesh', 'Jim', 'OSCAR', 'TIDE', 'Moh', 'Lui', 'Santa', 'Charlie']
7
['Charlie', 'Jim', 'Lui', 'Mahesh', 'Moh', 'NEWFRIEND', 'OSCAR', 'Santa', 'TIDE']

All friends cleared:
[]

Process finished with exit code 0

 

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments